ads_handler.go 23 KB

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