ads_handler.go 21 KB

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