ads_handler.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/gin-gonic/gin"
  6. "math/rand"
  7. "miads/adslib"
  8. "miads/adslib/addata"
  9. "miads/adslib/ads_checker"
  10. "miads/adslib/city"
  11. "miads/adslib/device"
  12. "miads/adslib/encrypt"
  13. "miads/adslib/graylog"
  14. "miads/adslib/ip2region"
  15. "miads/adslib/redis_data"
  16. "miads/adslib/utils"
  17. "net/url"
  18. "strconv"
  19. "strings"
  20. "time"
  21. log "github.com/sirupsen/logrus"
  22. )
  23. type Response struct {
  24. Result int `json:"result"`
  25. Msg string `json:"msg"`
  26. AdsResult string `json:"ads_result"`
  27. addata.AdData
  28. }
  29. func adsHandler(c *gin.Context) {
  30. c.Header("Content-Type", "application/json")
  31. request := adslib.Request{}
  32. request.Parse(c)
  33. log.Printf("%+v", request)
  34. // 放这里主要为了拿到reqeust id做日志记录
  35. dspInfo := utils.DspParam{}
  36. dspInfo.Init()
  37. advertiser := "xiaomi"
  38. uaClient := request.UaClient
  39. // 获取ua
  40. if uaClient == "" {
  41. uaClient = c.GetHeader("User-Agent")
  42. if uaClient == "" {
  43. uaClient = "Dalvik/2.1.0 (Linux; U; Android 6.0.1; MI 4LTE MIUI/6.9.1)"
  44. }
  45. }
  46. // 获取ip
  47. checkReqSourceFlag, err := ads_checker.CheckReqSource(request.ReqSource)
  48. if err != nil {
  49. c.String(404, "check req source failed: %s", err)
  50. return
  51. }
  52. ip := ""
  53. if checkReqSourceFlag {
  54. ip = request.ReqSourceIp
  55. }
  56. if ip == "" {
  57. ip = c.GetHeader("X-Forwarded-For")
  58. }
  59. if ip == "" {
  60. ip = c.GetHeader("X-Real-IP")
  61. }
  62. if ip == "" {
  63. ip = c.Request.RemoteAddr
  64. }
  65. if strings.Index(ip, ",") != -1 {
  66. ip = strings.Split(ip, ",")[0]
  67. }
  68. ipInfo, err := ip2region.Ip2Region(ip)
  69. if err != nil {
  70. c.String(404, "ip 2 region failed: %s", err)
  71. return
  72. }
  73. fmt.Printf("ip 2 region: %s, %+v\n", ip, ipInfo)
  74. // 上報
  75. if request.NewAdsFlag == 1 {
  76. grayLogData := struct {
  77. Ip string
  78. Imei string
  79. Model string
  80. NetworkType int `json:"network_type"`
  81. Province string
  82. City string
  83. ScreeSize string `json:"screen_size"`
  84. Ua string
  85. Brand string
  86. Androidid string `json:"android_id"`
  87. ShortMessage string `json:"short_message"`
  88. ReqSource string `json:"req_source"`
  89. Hehe string `json:"hehe"`
  90. }{
  91. Ip: ip,
  92. Imei: request.Imei,
  93. Model: request.Model,
  94. NetworkType: request.NetworkType,
  95. Province: ipInfo.Province,
  96. City: ipInfo.City,
  97. ScreeSize: request.ScreenSize,
  98. Ua: request.UaClient,
  99. Brand: request.Brand,
  100. Androidid: request.Androidid,
  101. ShortMessage: "ads_api_log",
  102. ReqSource: "zhiku",
  103. Hehe: "heheheheh",
  104. }
  105. graylog.Log(grayLogData)
  106. }
  107. // 定制city code
  108. cityCode, err := city.GetCityCode(ipInfo.City)
  109. log.WithField("request_id", dspInfo.RequestId).Infof("got city code: %d", cityCode)
  110. if err != nil {
  111. c.String(404, "get city code failed: %s", err)
  112. return
  113. }
  114. freqControlInterval := 600
  115. // 深圳,东莞强行用600秒控制, 其他地区从配置读取
  116. if strings.Index(ipInfo.City, "深圳") == -1 && strings.Index(ipInfo.City, "东莞") == -1 {
  117. // 频率控制
  118. freqControlConf, err := redis_data.GetFreqControlConf(request.ReqSource)
  119. if err != nil {
  120. log.WithField("request_id", dspInfo.RequestId).Errorf("get freq control conf failed: %s", err)
  121. c.String(404, "get freq control conf failed: %s", err)
  122. return
  123. }
  124. log.WithField("request_id", dspInfo.RequestId).Infof("freq control conf: %+v", freqControlConf)
  125. hour, _ := strconv.Atoi(time.Now().Format("01"))
  126. tmpControlInterval, ok := freqControlConf.GetControlTime(hour)
  127. if ok {
  128. freqControlInterval = tmpControlInterval
  129. }
  130. }
  131. lastReqTime, err := device.GetIpReqTime(ip)
  132. if err != nil {
  133. fmt.Println(err)
  134. c.String(404, "get last req time failed: %s", err)
  135. return
  136. }
  137. needControl := false
  138. if request.ReqSource != "wzb_h5" && lastReqTime != 0 && time.Now().Unix()-lastReqTime < int64(freqControlInterval) {
  139. // 需要凭空
  140. log.WithField("request_id", dspInfo.RequestId).Infof("need control: %d", lastReqTime)
  141. needControl = true
  142. device.SetAdsTagLog(advertiser, request.ReqSource, "DS_FREQ_0", cityCode)
  143. } else {
  144. device.SetIpReqTime(ip, time.Now().Unix())
  145. device.SetAdsTagLog(advertiser, request.ReqSource, "DS_FREQ_1", cityCode)
  146. }
  147. //### 检查是否是ip黑名单
  148. isIpBlack, err := ads_checker.CheckBlackIp(ip)
  149. if err != nil {
  150. log.WithField("request_id", dspInfo.RequestId).Errorf("check black ip failed: %s", err)
  151. c.String(404, "check black ip failed: %s", err)
  152. return
  153. }
  154. if isIpBlack {
  155. graylog.LogApi("black_ip_list", ip, "", request.ReqSource)
  156. device.SetAdsTagLog(advertiser, request.ReqSource, "DS_BLACK_IP", cityCode)
  157. }
  158. // 获取渠道的黑白性
  159. reqChannelFlag, err := redis_data.GetChannelFlag(request.ReqSource, "ads_req")
  160. if err != nil {
  161. log.WithField("request_id", dspInfo.RequestId).Errorf("get req channel flag failed: %s", err)
  162. c.String(404, "get req channel flag failed: %s", err)
  163. return
  164. }
  165. flowWeight := reqChannelFlag.Weigth
  166. flowRandomNum := rand.Intn(100)
  167. flowFlag := 0 // 有效的百分比
  168. if flowRandomNum <= flowWeight {
  169. flowFlag = 1
  170. }
  171. if reqChannelFlag.ChannelFlag == 1 {
  172. device.SetAdsTagLog(advertiser, request.ReqSource, fmt.Sprintf("DS_REQ_SOURCE_{%d}", reqChannelFlag.ChannelFlag), cityCode)
  173. }
  174. // 替换成小米的设备
  175. replaceFlag := 0
  176. imei := request.Imei
  177. sendPhoneType := 0
  178. userFlag := 0
  179. originImei := ""
  180. // 检查是否是小米的设备
  181. specialDeviceNum := 0
  182. if request.ReqSource == "wzb_h5" {
  183. specialDeviceNum = 6 // wzb_h5渠道只綁定一个imei, 具体愿意不知道
  184. }
  185. if request.ReqSource == "moyuntv" || (!request.IsMiDevice() &&
  186. (!isIpBlack && !needControl && reqChannelFlag.ChannelFlag == 1) && flowFlag == 1) {
  187. randomNum := 3
  188. deviceConf, realRedisKey, err := device.GetMiDeviceConf(ip, randomNum, specialDeviceNum)
  189. if err != nil {
  190. log.WithField("request_id", dspInfo.RequestId).Errorf("get mi device conf failed: %s", err)
  191. c.String(404, "get mi device conf failed: %s", err)
  192. return
  193. }
  194. if deviceConf != nil {
  195. log.WithField("request_id", dspInfo.RequestId).Infof("use cache imei: %+v", deviceConf)
  196. device.SetAdsTagLog(advertiser, request.ReqSource, "DS_CACHE", cityCode) // 通过缓存请求
  197. imei = deviceConf.Imei
  198. uaClient = deviceConf.Ua
  199. originImei = deviceConf.OriginImei
  200. if imei != "" {
  201. replaceFlag = 1
  202. userFlag = 1
  203. }
  204. } else {
  205. // 先从对应的城市找,找不到在走原来的逻辑
  206. // 上报事件
  207. graylog.LogApi("city_search_city_code", strconv.Itoa(cityCode), ipInfo.City, request.ReqSource)
  208. device.SetAdsTagLog(advertiser, request.ReqSource, "DS_CODE_REQ", cityCode) // 可做城市替换
  209. if cityCode != 0 {
  210. device.SetAdsTagLog(advertiser, request.ReqSource, "DS_CODE", cityCode) // 替换成功
  211. fakeImei := ""
  212. fakeDeviceConf, leftCnt, err := device.GetDailyFakeDeviceConfByCityCode(cityCode)
  213. if err != nil {
  214. log.WithField("request_id", dspInfo.RequestId).Errorf("get device conf failed: %s", err)
  215. c.String(404, "get device conf failed: %s", err)
  216. return
  217. }
  218. // 0 没有获取到, 1 获取到了
  219. gotCityFakeDeviceConfFlag := 0
  220. replaceUa := ""
  221. if fakeDeviceConf != nil {
  222. device.SetAdsTagLog(advertiser, request.ReqSource, "DS_REPL", cityCode)
  223. err := device.SetMiDeviceConf(realRedisKey, *fakeDeviceConf)
  224. if err != nil {
  225. log.WithField("request_id", dspInfo.RequestId).Errorf("set mi device conf failed: %s", err)
  226. }
  227. imei = fakeDeviceConf.Imei
  228. uaClient = fakeDeviceConf.Ua
  229. originImei = fakeDeviceConf.OriginImei
  230. fakeImei = fakeDeviceConf.Imei
  231. if fakeDeviceConf.Imei != "" {
  232. gotCityFakeDeviceConfFlag = 1
  233. userFlag = 2
  234. replaceFlag = 1
  235. }
  236. }
  237. grayLogData := struct {
  238. ReqSource string `json:"req_source"`
  239. OldImei string `json:"old_imei"`
  240. NewImei string `json:"new_imei"`
  241. IP string `json:"ip"`
  242. City string `json:"city"`
  243. CityCode int `json:"city_code"`
  244. Province string
  245. HitFlag int `json:"hit_flag"`
  246. LeftCnt int `json:"left_cnt"`
  247. ReplaceUa string `json:"replace_ua"`
  248. ShortMessage string `json:"short_message"`
  249. }{
  250. ReqSource: request.ReqSource,
  251. OldImei: request.Imei,
  252. NewImei: fakeImei,
  253. IP: ip,
  254. City: ipInfo.City,
  255. CityCode: cityCode,
  256. Province: ipInfo.Province,
  257. HitFlag: gotCityFakeDeviceConfFlag,
  258. LeftCnt: leftCnt,
  259. ReplaceUa: replaceUa,
  260. ShortMessage: "",
  261. }
  262. // 进行日志的上报
  263. graylog.Log(grayLogData)
  264. }
  265. }
  266. // 解码ua_client
  267. uaClient, _ = url.QueryUnescape(uaClient)
  268. } else if request.IsMiDevice() {
  269. log.WithField("request_id", dspInfo.RequestId).Info("real mi")
  270. device.SetAdsTagLog(advertiser, request.ReqSource, "DS_MI_REAL", cityCode) // 是小米设备
  271. userFlag = 3
  272. sendPhoneType = 1
  273. }
  274. // 检查下,替换后的设备是否是黑名单, 再次检查, 防止放入cache后, 新增了黑名单
  275. checkImei := imei
  276. // 替换过的imei从redis取的, 都是md5后的, 不需要再md5
  277. if replaceFlag != 1 {
  278. checkImei = utils.Md5(imei)
  279. }
  280. isBlackImei, err := device.CheckIsBlackImei(checkImei)
  281. if err != nil {
  282. log.WithField("request_id", dspInfo.RequestId).Errorf("get device conf failed: %s", err)
  283. c.String(404, "get device conf failed: %s", err)
  284. return
  285. }
  286. log.WithField("request_id", dspInfo.RequestId).Tracef("replace flag: %d", replaceFlag)
  287. if isBlackImei {
  288. if replaceFlag == 1 {
  289. log.WithField("request_id", dspInfo.RequestId).Trace("replace")
  290. device.SetAdsTagLog(advertiser, request.ReqSource, "DS_BLACK_IMEI_REPLACE", cityCode)
  291. } else {
  292. log.WithField("request_id", dspInfo.RequestId).Trace("not replace")
  293. device.SetAdsTagLog(advertiser, request.ReqSource, "DS_BLACK_IMEI", cityCode)
  294. }
  295. }
  296. // 组装公共的dsp_info
  297. dspInfo.DspCityCode = cityCode
  298. dspInfo.Imei = imei
  299. dspInfo.OriginImei = originImei
  300. dspInfo.OsVersion = request.OsVersion
  301. dspInfo.Mac = strings.ToUpper(request.Mac)
  302. dspInfo.OriginMac = request.Mac
  303. dspInfo.Idfa = request.Idfa
  304. dspInfo.Model = request.Model
  305. dspInfo.Brand = request.Brand
  306. dspInfo.ScreenSize = request.ScreenSize
  307. dspInfo.NetworkType = request.NetworkType
  308. dspInfo.Androidid = request.Androidid
  309. dspInfo.Platform = request.Platform
  310. dspInfo.Ip = ip
  311. dspInfo.Ua = uaClient
  312. dspInfo.City = ipInfo.City
  313. dspInfo.Province = ipInfo.Province
  314. dspInfo.UaOrigin = request.UaClient
  315. dspInfo.ReqSource = request.ReqSource
  316. if request.IsMiDevice() {
  317. dspInfo.RealMiFlag = 1
  318. }
  319. dspInfo.ReplaceFlag = replaceFlag
  320. dspInfo.RealReqSource = request.ReqSource
  321. dspInfo.SendPhoneType = sendPhoneType
  322. md5Imei := imei
  323. if dspInfo.OriginImei != "" {
  324. md5Imei = utils.Md5(dspInfo.OriginImei)
  325. }
  326. dspInfo.RealMd5Imei = md5Imei
  327. log.WithField("request_id", dspInfo.RequestId).Infof("dsp: %+v", dspInfo)
  328. //ads_item = None
  329. //xiaomi_response = []
  330. hour, _ := strconv.Atoi(time.Now().Format("01"))
  331. canRequest := true
  332. if 0 <= hour && hour <= 1 {
  333. randNum := rand.Intn(100)
  334. if randNum > 5 {
  335. canRequest = false
  336. }
  337. }
  338. log.WithField("request_id", dspInfo.RequestId).Infof("can request: %t", canRequest)
  339. var adData *addata.AdData
  340. // 非频率控制,设备黑名单,ip黑名单,白名单渠道,并且替换了小米设备的
  341. if canRequest && !isBlackImei && reqChannelFlag.ChannelFlag == 1 && flowFlag == 1 && !isIpBlack && advertiser == "xiaomi" && request.ReqSource != "" && !needControl && (replaceFlag == 1 || request.IsMiDevice()) {
  342. adData, err = addata.GetAdsInfos(&dspInfo, advertiser)
  343. if err != nil {
  344. log.WithField("request_id", dspInfo.RequestId).Errorf("get mi ad data failed: %s", err)
  345. c.String(404, "get mi ad data failed: %s", err)
  346. return
  347. }
  348. log.WithField("request_id", dspInfo.RequestId).Infof("get mi ads data: %+v", adData)
  349. }
  350. canMixFlag := 1
  351. xiaomiResponseFlag := 0
  352. response := Response{}
  353. response.Msg = "ok"
  354. if adData != nil && len(adData.TargetAddition) > 1 {
  355. log.WithField("request_id", dspInfo.RequestId).Infof("add target js order")
  356. xiaomiResponseFlag = 1
  357. realTarget := ""
  358. if adData.Target != "" {
  359. md5Skip := utils.Md5(adData.Target)
  360. conf := adslib.GetConf()
  361. realTarget = conf.Host + fmt.Sprintf("?action=LOADING&req_source=%s&advertiser=video&skip=%s&brand=%s&request_id=%s&skip_other=%s",
  362. dspInfo.ReqSource, "", dspInfo.Brand, dspInfo.RequestId, md5Skip)
  363. // 塞入Redis中
  364. redis_data.SetSkipInfo(md5Skip, adData.Target)
  365. }
  366. adData.Target = realTarget
  367. adData.JsOrderId, err = redis_data.GetMinScriptOrderByAdv(advertiser)
  368. if err != nil {
  369. log.WithField("request_id", dspInfo.RequestId).Errorf("get min script order by adv failed: %s", err)
  370. c.String(404, "get min script order by adv failed: %s", err)
  371. return
  372. }
  373. log.WithField("request_id", dspInfo.RequestId).Infof("got min script order: %d", adData.JsOrderId)
  374. adData.UserAgent = uaClient
  375. if dspInfo.ReqSource == "kuxin" && adData.Target != "" {
  376. adData.DpReport = fmt.Sprintf("%s?action=DP_CLICK&advertiser=video&req_source=%s", adslib.GetConf().HostIos, dspInfo.ReqSource)
  377. adData.Dp = adslib.GetConf().DpTest
  378. }
  379. if dspInfo.SendPhoneType == 0 {
  380. device.SetAdsTagLog(advertiser, dspInfo.ReqSource, "ADS_GET", cityCode) // 广告获取成功
  381. } else if dspInfo.SendPhoneType == 1 {
  382. device.SetAdsTagLog(advertiser, dspInfo.ReqSource, "ADS_GET_1", cityCode) // 广告获取成功
  383. }
  384. device.SetAdsTagLog(advertiser, dspInfo.ReqSource, fmt.Sprintf("ADS_USER_%d", userFlag), cityCode) // 广告类型,缓存,新用户,小米手机
  385. // // 判断这个渠道是否要去融合和融合的流量占比
  386. // mixChannelFlag, err := redis_data.GetChannelFlag(dspInfo.ReqSource, "ads_mix")
  387. // if err != nil {
  388. // log.WithField("request_id", dspInfo.RequestId).Errorf("get device conf failed: %s", err)
  389. // c.String(404, "get device conf failed: %s", err)
  390. // return
  391. // }
  392. // flowRandomNum = rand.Intn(100)
  393. //isOverFlow := false
  394. //if flowRandomNum > mixChannelFlag.Weigth {
  395. // isOverFlow = true
  396. //}
  397. //if mixChannelFlag.ChannelFlag != 1 || isOverFlow {
  398. // //extra_infos = []
  399. //}
  400. // 组装返回去的action
  401. serverActionResponse := map[string]int{"server_view": 0, "server_click": 0, "server_close": 0, "server_video_finish": 0, "server_video_timer": 0}
  402. for _, targetInfo := range adData.TargetAddition {
  403. if targetInfo.Type == "VIEW" {
  404. serverActionResponse["server_view"] = 1
  405. redis_data.SetReqSourceView(advertiser, dspInfo.ReqSource, "xiafa")
  406. } else if targetInfo.Type == "CLICK" {
  407. serverActionResponse["server_click"] = 1
  408. } else if targetInfo.Type == "CLOSE" {
  409. serverActionResponse["server_close"] = 1
  410. } else if targetInfo.Type == "VIDEO_FINISH" {
  411. serverActionResponse["server_video_finish"] = 1
  412. } else if targetInfo.Type == "VIDEO_TIMER" {
  413. serverActionResponse["server_video_timer"] = 1
  414. }
  415. }
  416. log.WithField("request_id", dspInfo.RequestId).Infof("server action response: %+v", serverActionResponse)
  417. // 增加跟随订单
  418. if len(adData.TargetAddition) == 2 && serverActionResponse["server_video_finish"] == 1 && (dspInfo.ReqSource == "kuxin" || dspInfo.ReqSource == "zhiku") {
  419. log.WithField("request_id", dspInfo.RequestId).Infof("add more order")
  420. adData, err = addata.CombineOrderBy(adData, &dspInfo)
  421. if err != nil {
  422. log.WithField("request_id", dspInfo.RequestId).Errorf("combine order failed: %s", err)
  423. c.String(404, "combine order failed: %s", err.Error())
  424. return
  425. }
  426. log.WithField("request_id", dspInfo.RequestId).Infof("get custom order: %+v", adData)
  427. }
  428. //# 检查最后是否有click
  429. log.WithField("request_id", dspInfo.RequestId).Infof("check ads item new: %+v", adData)
  430. for _, targetAddition := range adData.TargetAddition {
  431. if targetAddition.Type == "CLICK" || targetAddition.Type == "VIDEO_TIMER" {
  432. log.WithField("request_id", dspInfo.RequestId).Infof("can't mix, targetAddition: %+v", targetAddition)
  433. canMixFlag = 0
  434. break
  435. }
  436. }
  437. if request.NewAdsFlag == 0 {
  438. response.AdData = *adData
  439. log.WithField("request_id", dspInfo.RequestId).Infof("update response: +%v", response)
  440. } else {
  441. jsonBytes, err := json.Marshal(*adData)
  442. if err != nil {
  443. c.String(404, "marshal AdData failed: %s", err.Error())
  444. return
  445. }
  446. encryptData, _ := encrypt.Encrypt(jsonBytes, []byte(adslib.GetConf().SecretKey))
  447. response.AdsResult = encryptData
  448. }
  449. }
  450. log.WithField("request_id", dspInfo.RequestId).Infof("can mix: %d, xiaomi rsp flag: %d", canMixFlag, xiaomiResponseFlag)
  451. if canMixFlag == 1 {
  452. response.Result = 2
  453. response.Msg = "no ads"
  454. if xiaomiResponseFlag == 1 {
  455. response.Result = 0
  456. response.Msg = "ok"
  457. }
  458. // 增加打底广告
  459. if (dspInfo.ReqSource == "kuxin" || dspInfo.ReqSource == "zhiku") && !needControl && !isBlackImei {
  460. shortMessage := "kong"
  461. // 先跑定投
  462. customAdData, err := addata.GetCustomAdsInfos(&dspInfo, 0, 0, xiaomiResponseFlag)
  463. if err != nil {
  464. log.WithField("request_id", dspInfo.RequestId).Infof("get custom ads info failed: %s", err)
  465. c.String(404, "get custom ads info failed: %s", err.Error())
  466. return
  467. }
  468. log.WithField("request_id", dspInfo.RequestId).Infof("dingtou: %+v", customAdData)
  469. // 定投没有就跑其他的
  470. if customAdData == nil {
  471. customAdData, err = addata.GetCustomAdsInfos(&dspInfo, 0, 1, xiaomiResponseFlag)
  472. if err != nil {
  473. log.WithField("request_id", dspInfo.RequestId).Errorf("get fix custom ads info failed: %s", err)
  474. c.String(404, "get fix custom ads info failed: %s", err.Error())
  475. return
  476. }
  477. }
  478. device.SetAdsTagLog(advertiser, dspInfo.ReqSource, "ADS_ZIYOU_GET", cityCode) // 广告获取成功
  479. if customAdData != nil {
  480. shortMessage = "ads_tt_thirds"
  481. }
  482. if customAdData != nil && (shortMessage == "ads_vast_response" || shortMessage == "ads_tt_thirds") {
  483. adDataBytes, err := json.Marshal(*customAdData)
  484. if err != nil {
  485. log.WithField("request_id", dspInfo.RequestId).Errorf("marshal adData failed: %s\n", err)
  486. }
  487. grayLogData := struct {
  488. Ip string
  489. ShortMessage string `json:"short_message"`
  490. ReqSource string `json:"req_source"`
  491. ResponseVast string `json:"response_vast"`
  492. OrderName string `json:"order_name"`
  493. Advertiser string `json:"advertiser"`
  494. }{
  495. Ip: ip,
  496. ShortMessage: "ads_api_log",
  497. ReqSource: "zhiku",
  498. ResponseVast: string(adDataBytes),
  499. OrderName: customAdData.OrderName,
  500. Advertiser: advertiser,
  501. }
  502. graylog.Log(grayLogData)
  503. }
  504. if shortMessage == "ads_tt_thirds" {
  505. // 组装最后的信息
  506. lastAdData := addata.AdData{}
  507. rspTargetAddition := make([]addata.AdAction, 0, 50)
  508. // 当小米有填充的时候
  509. if len(response.TargetAddition) != 0 && len(customAdData.TargetAddition) != 0 {
  510. rspTargetAddition = response.TargetAddition
  511. lastAdData.UserAgent = response.UserAgent
  512. // 当只有view的时候
  513. if len(customAdData.TargetAddition) == 1 {
  514. for _, targetUrl := range customAdData.TargetAddition[0].Urls {
  515. rspTargetAddition[0].Urls = append(rspTargetAddition[0].Urls, targetUrl)
  516. }
  517. } else {
  518. // 当自由订单有view和click的时候
  519. for _, targetUrl := range customAdData.TargetAddition[0].Urls {
  520. rspTargetAddition[0].Urls = append(rspTargetAddition[0].Urls, targetUrl)
  521. }
  522. for _, targetUrl := range customAdData.TargetAddition[1].Urls {
  523. rspTargetAddition[1].Urls = append(rspTargetAddition[1].Urls, targetUrl)
  524. }
  525. rspTargetAddition[1].Type = "CLICK"
  526. }
  527. lastAdData.Target = customAdData.Target
  528. lastAdData.JsOrderId = customAdData.JsOrderId
  529. lastAdData.TargetAddition = rspTargetAddition
  530. lastAdData.DpReport = response.DpReport
  531. lastAdData.Dp = response.Dp
  532. adDataBytes, err := json.Marshal(lastAdData)
  533. if err != nil {
  534. log.WithField("request_id", dspInfo.RequestId).Errorf("marshal adData failed: %s", err)
  535. }
  536. grayLogData := struct {
  537. ShortMessage string `json:"short_message"`
  538. ResponseVast string `json:"response_vast"`
  539. }{
  540. ShortMessage: "third_mix_xiaomi",
  541. ResponseVast: string(adDataBytes),
  542. }
  543. graylog.Log(grayLogData)
  544. log.WithField("request_id", dspInfo.RequestId).Infof("replace addata: %+v", lastAdData)
  545. customAdData = &lastAdData
  546. }
  547. }
  548. if customAdData != nil {
  549. device.SetAdsTagLog(advertiser, dspInfo.ReqSource, "ADS_ZIYOU_HAVE", cityCode) // 广告获取成功
  550. if dspInfo.ReqSource == "zhiku" {
  551. response.Result = 0
  552. response.Msg = "ok"
  553. log.WithField("request_id", dspInfo.RequestId).Infof("rsp1: %+v", customAdData)
  554. jsonBytes, err := json.Marshal(customAdData)
  555. if err != nil {
  556. log.WithField("request_id", dspInfo.RequestId).Errorf("marshal rsp1 custom ad failed: %s", err)
  557. c.String(404, "marsha custom addata failed: %s", err.Error())
  558. return
  559. }
  560. log.WithField("request_id", dspInfo.RequestId).Infof("rsp1: %s", jsonBytes)
  561. encryptData, _ := encrypt.Encrypt(jsonBytes, []byte(adslib.GetConf().SecretKey))
  562. response.AdsResult = encryptData
  563. log.WithField("request_id", dspInfo.RequestId).Infof("encrypt: %s", encryptData)
  564. s, err := encrypt.Decrypt(encryptData, []byte(adslib.GetConf().SecretKey))
  565. log.WithField("request_id", dspInfo.RequestId).Info(s, err)
  566. graylog.ReportGrayLog(request, dspInfo, 0, 0)
  567. rspBytes, err := json.Marshal(response)
  568. if err != nil {
  569. log.WithField("request_id", dspInfo.RequestId).Errorf("marshal rsp1 failed: %s", err)
  570. c.String(404, "marshal Response failed: %s", err.Error())
  571. return
  572. }
  573. log.WithField("request_id", dspInfo.RequestId).Infof("rsp1: %s", rspBytes)
  574. c.String(200, string(rspBytes))
  575. return
  576. } else {
  577. customAdData.Result = 0
  578. customAdData.Msg = "ok"
  579. graylog.ReportGrayLog(request, dspInfo, 0, 0)
  580. rspBytes, err := json.Marshal(customAdData)
  581. if err != nil {
  582. log.WithField("request_id", dspInfo.RequestId).Errorf("marshal rsp2 failed: %s", err)
  583. c.String(404, err.Error())
  584. return
  585. }
  586. log.WithField("request_id", dspInfo.RequestId).Infof("rsp2: %s", rspBytes)
  587. c.String(200, string(rspBytes))
  588. return
  589. }
  590. }
  591. }
  592. }
  593. redis_data.SetAdsRealRequestNum(advertiser)
  594. rspBytes, err := json.Marshal(response)
  595. if err != nil {
  596. log.WithField("request_id", dspInfo.RequestId).Errorf("marshal rsp3 failed: %s", err)
  597. c.String(404, err.Error())
  598. return
  599. }
  600. if request.NewAdsFlag == 0 {
  601. graylog.ReportGrayLog(request, dspInfo, 0, 0)
  602. }
  603. device.SetAdsTagLog(advertiser, dspInfo.ReqSource, "DS_REQ", cityCode) // 所有请求
  604. log.WithField("request_id", dspInfo.RequestId).Infof("rsp3: %s", rspBytes)
  605. c.String(200, string(rspBytes))
  606. }