xiaomi.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. package addata
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. log "github.com/sirupsen/logrus"
  6. "html"
  7. "io/ioutil"
  8. "math/rand"
  9. "miads/adslib"
  10. "miads/adslib/device"
  11. "miads/adslib/redis_data"
  12. "miads/adslib/utils"
  13. "net/http"
  14. "net/url"
  15. "strconv"
  16. "strings"
  17. )
  18. type XiaomiAdData struct {
  19. DetailURL string `json:"detail_url"`
  20. DisplayType struct {
  21. Delay int64 `json:"delay"`
  22. Name string `json:"name"`
  23. RowCount int64 `json:"row_count"`
  24. } `json:"display_type"`
  25. Duration int64 `json:"duration"`
  26. EmcType string `json:"emc_type"`
  27. ID string `json:"id"`
  28. ImageURL string `json:"image_url"`
  29. Proportion string `json:"proportion"`
  30. Settings struct {
  31. ClickType string `json:"click_type"`
  32. HideCloseAt int64 `json:"hide_close_at"`
  33. LogTime string `json:"log_time"`
  34. ShowCloseAt int64 `json:"show_close_at"`
  35. } `json:"settings"`
  36. SkipTime int64 `json:"skip_time"`
  37. TagID string `json:"tag_id"`
  38. Target string `json:"target"`
  39. TargetAddition []string `json:"target_addition"`
  40. TargetAddition1 string `json:"target_addition1"`
  41. Title string `json:"title"`
  42. VideoURL string `json:"video_url"`
  43. }
  44. type XiaoMiAdInfoRsp struct {
  45. Data []XiaomiAdData `json:"data"`
  46. Msg string `json:"msg"`
  47. Result int64 `json:"result"`
  48. }
  49. type AdAction struct {
  50. Type string `json:"type"`
  51. Duration int `json:"duration"`
  52. Urls []string `json:"urls"`
  53. }
  54. type AdInfo struct {
  55. AdActions []AdAction `json:"ads_infos"`
  56. PercentBegin int `json:"percent_begin"`
  57. PercentEnd int `json:"percent_end"`
  58. }
  59. type AdData struct {
  60. TargetAddition []AdAction `json:"target_addition,omitempty"`
  61. Target string `json:"target,omitempty"`
  62. ImageUrl string `json:"image_url,omitempty"`
  63. Duration int64 `json:"duration,omitempty"`
  64. VideoUrl string `json:"video_url,omitempty"`
  65. JsOrderId int64 `json:"js_order_id,omitempty"`
  66. UserAgent string `json:"user_agent,omitempty"`
  67. DpReport string `json:"dp_report,omitempty"`
  68. Dp string `json:"dp,omitempty"`
  69. OrderName string `json:"order_name,omitempty"`
  70. Result int `json:"result"`
  71. Msg string `json:"msg"`
  72. }
  73. func getAdsReqUrl(dsp *utils.DspParam) string {
  74. reqUrl := "https://m.video.xiaomi.com/api/a3/otv_emc?"
  75. ref := "yilin"
  76. sn := "05817a33d4210ad2c67f4b869b5eedde"
  77. // 组装 emcp
  78. reqUrl = reqUrl + "_emcp=pre_play"
  79. // 组装 devid
  80. reqUrl = reqUrl + "&_devid=" + dsp.RealMd5Imei
  81. // 组装 ref
  82. reqUrl = reqUrl + "&ref=" + ref
  83. // 组装 sn
  84. reqUrl = reqUrl + "&_sn=" + sn
  85. // 组装 ip
  86. reqUrl = reqUrl + "&__ip__=" + dsp.Ip
  87. rad := rand.Intn(100)
  88. if rad < 15 {
  89. dsp.SendPhoneType = 1
  90. } else {
  91. dsp.SendPhoneType = 0
  92. }
  93. reqUrl = reqUrl + fmt.Sprintf("&_phonetype=%d", dsp.SendPhoneType)
  94. return reqUrl
  95. }
  96. // 获取广告信息
  97. func GetAdsInfos(dsp *utils.DspParam, advertiser string) (*AdData, error) {
  98. reqUrl := getAdsReqUrl(dsp)
  99. if dsp.SendPhoneType == 0 {
  100. device.SetAdsTagLog("xiaomi", dsp.ReqSource, "ADS_XIAOMI", dsp.DspCityCode)
  101. } else if dsp.SendPhoneType == 1 {
  102. device.SetAdsTagLog("xiaomi", dsp.ReqSource, "ADS_XIAOMI_1", dsp.DspCityCode)
  103. }
  104. client := &http.Client{}
  105. log.WithField("request_id", dsp.RequestId).Infof("req url: %s", reqUrl)
  106. req, err := http.NewRequest("GET", reqUrl, nil)
  107. if err != nil {
  108. return nil, err
  109. }
  110. req.Header.Set("authority", "m.video.xiaomi.com")
  111. req.Header.Set("method", "GET")
  112. req.Header.Set("path", reqUrl[26:])
  113. req.Header.Set("scheme", "https")
  114. req.Header.Set("content-type", "application/json")
  115. req.Header.Set("accept-language", "zh-CN,zh;q=0.9")
  116. req.Header.Set("cache-control", "max-age=0")
  117. req.Header.Set("upgrade-insecure-requests", "1")
  118. req.Header.Set("user-agent", dsp.Ua)
  119. resp, err := client.Do(req)
  120. if err != nil {
  121. log.WithField("request_id", dsp.RequestId).Errorf("http failed: %s", err)
  122. return nil, err
  123. }
  124. defer resp.Body.Close()
  125. body, err := ioutil.ReadAll(resp.Body)
  126. if err != nil {
  127. log.WithField("request_id", dsp.RequestId).Errorf("read http body failed: %s", err)
  128. return nil, err
  129. }
  130. log.WithField("request_id", dsp.RequestId).Infof("rsp: %s", string(body))
  131. rsp := XiaoMiAdInfoRsp{}
  132. err = json.Unmarshal([]byte(string(body)), &rsp)
  133. if err != nil {
  134. log.WithField("request_id", dsp.RequestId).Errorf("unmarshal http rsp failed: %s, rsp: %s", err, string(body))
  135. return nil, err
  136. }
  137. adsDataNum := len(rsp.Data)
  138. xiaomiResponseAction := map[string]int{
  139. "xiaomi_view": 0, "xiaomi_click": 0, "xiaomi_close": 0, "xiaomi_video_finish": 0, "xiaomi_video_timer": 0,
  140. }
  141. if rsp.Result != 1 {
  142. return nil, nil
  143. }
  144. // bom渠道不处理
  145. if dsp.ReqSource != "bom" {
  146. rad := rand.Intn(100)
  147. if rad < 2 {
  148. dsp.ReqSource = "kk_h5"
  149. } else if rad < 4 {
  150. dsp.ReqSource = "day_09"
  151. } else if rad < 8 {
  152. dsp.ReqSource = "fu008"
  153. } else if rad < 9 {
  154. dsp.ReqSource = "yzh01"
  155. } else if rad < 11 {
  156. dsp.ReqSource = "qihuang88"
  157. }
  158. }
  159. if len(rsp.Data) == 0 {
  160. return nil, nil
  161. }
  162. ///last_infos = xiaomi_mix.xiaomi_fuse(data, dsp.req_source)
  163. dataInfo := rsp.Data[0]
  164. dsp.AllDuration = dataInfo.Duration
  165. dsp.VideoTimeDuration = 7
  166. showUrls := make([]string, 0, 100)
  167. clickUrls := make([]string, 0, 100)
  168. closeUrls := make([]string, 0, 100)
  169. videoFinishUrls := make([]string, 0, 100)
  170. videoTimerUrls := make([]string, 0, 100)
  171. for _, target := range rsp.Data[0].TargetAddition {
  172. target := html.UnescapeString(target)
  173. targetParseUrl, err := url.Parse(target)
  174. if err != nil {
  175. log.WithField("request_id", dsp.RequestId).Errorf("parse url failed, url: %s, err: %s", target, err)
  176. continue
  177. }
  178. targetParams := targetParseUrl.Query()
  179. targetUrl := targetParams.Get("url")
  180. event := targetParams.Get("event")
  181. if targetUrl != "" {
  182. switch event {
  183. case "VIEW":
  184. showUrls = append(showUrls, targetUrl)
  185. xiaomiResponseAction["xiaomi_view"] = 1
  186. case "CLICK":
  187. clickUrls = append(clickUrls, targetUrl)
  188. xiaomiResponseAction["xiaomi_click"] = 1
  189. case "CLOSE":
  190. closeUrls = append(closeUrls, targetUrl)
  191. xiaomiResponseAction["xiaomi_close"] = 1
  192. case "VIDEO_FINISH":
  193. videoFinishUrls = append(videoFinishUrls, targetUrl)
  194. xiaomiResponseAction["xiaomi_video_finish"] = 1
  195. case "VIDEO_TIMER":
  196. videoTimerUrls = append(videoTimerUrls, targetUrl)
  197. }
  198. }
  199. if event == "VIDEO_TIMER" {
  200. timeStr := targetParams.Get("time")
  201. if timeStr != "" {
  202. videoTimeDuration, _ := strconv.Atoi(timeStr)
  203. dsp.VideoTimeDuration = videoTimeDuration
  204. xiaomiResponseAction["xiaomi_video_timer"] = 1
  205. }
  206. }
  207. }
  208. gotoUrls := make([]string, 0, 100)
  209. target := rsp.Data[0].Target
  210. if target != "" {
  211. targetUrlObj, _ := url.Parse(target)
  212. targetParams := targetUrlObj.Query()
  213. targetUrl := targetParams.Get("link_url")
  214. if targetUrl == "" {
  215. targetUrl = strings.ReplaceAll(targetUrl, "mv:", "")
  216. }
  217. targetUrl = html.UnescapeString(targetUrl)
  218. if targetUrl != "" {
  219. gotoUrls = append(gotoUrls, targetUrl)
  220. }
  221. }
  222. if dsp.ReqSource == "mh" {
  223. closeUrls = videoFinishUrls
  224. }
  225. videoUrls := make([]string, 0, 100)
  226. videoUrl := rsp.Data[0].VideoURL
  227. if videoUrl != "" {
  228. videoUrls = append(videoUrls, videoUrl)
  229. }
  230. imageUrls := make([]string, 0, 100)
  231. imageUrl := rsp.Data[0].ImageURL
  232. if imageUrl != "" {
  233. imageUrls = append(imageUrls, imageUrl)
  234. }
  235. fmt.Printf("%+v, addata_num: %d\n", xiaomiResponseAction, adsDataNum)
  236. if len(gotoUrls) == 0 {
  237. return nil, nil
  238. }
  239. fmt.Printf("goto urls: %+v\nshow urls: %+v\nclick_urls: %+v\nclose urls: %+v\nvideo finish urls: %+v\nimagurls: %+v\nvideo urls:%+v\n",
  240. gotoUrls, showUrls, clickUrls, closeUrls, videoFinishUrls, imageUrls, videoUrls)
  241. adsData, err := CombineLastAdsInfos(dsp, advertiser, gotoUrls, showUrls, clickUrls, closeUrls, videoFinishUrls, videoTimerUrls, videoUrls)
  242. if err != nil {
  243. return nil, err
  244. }
  245. fmt.Printf("addata: %+v\n", adsData)
  246. if dsp.SendPhoneType == 0 {
  247. redis_data.SetAdsRequestNum(advertiser, 0)
  248. } else if dsp.SendPhoneType == 1 {
  249. redis_data.SetAdsRequestNum(advertiser, 1)
  250. }
  251. return adsData, nil
  252. }
  253. func getActionsConf(advertiser string) []string {
  254. defaultActions := []string{"VIEW", "CLICK", "CLOSE", "VIDEO_FINISH", "VIDEO_TIMER"}
  255. svrConf := adslib.GetConf()
  256. actions, ok := svrConf.AdsActions[advertiser]
  257. if !ok || len(actions) == 0 {
  258. return defaultActions
  259. }
  260. return actions
  261. }
  262. func getCombinationActionsConf(advertiser string) []adslib.CombinationActionsConf {
  263. svrConf := adslib.GetConf()
  264. combinationActions, ok := svrConf.CombinationActions[advertiser]
  265. if !ok {
  266. return []adslib.CombinationActionsConf{}
  267. }
  268. return combinationActions
  269. }
  270. // 组装最后的广告信息
  271. func CombineLastAdsInfos(dsp *utils.DspParam, advertiser string, gotoUrls []string, showUrls []string,
  272. clickUrls []string, closeUrls []string, videoFinishUrls []string,
  273. videoTimerUrls []string, videoUrls []string) (*AdData, error) {
  274. // 判断是不是关掉所有Action
  275. actions := getActionsConf(advertiser)
  276. if len(actions) == 0 {
  277. return nil, nil
  278. }
  279. clickChannelFlag, err := redis_data.GetChannelFlag(dsp.ReqSource, "ads_click")
  280. if err != nil {
  281. log.WithField("request_id", dsp.RequestId).Errorf("get ads_click channel flag failed: %s", err)
  282. return nil, err
  283. }
  284. log.WithField("request_id", dsp.RequestId).Tracef("click channel flag: %+v\n", clickChannelFlag)
  285. clickRandom := rand.Intn(100)
  286. needClick := false
  287. if clickChannelFlag.ChannelFlag == 1 && clickRandom <= clickChannelFlag.Weigth {
  288. needClick = true
  289. }
  290. lastInfos := make([]AdInfo, 0, 50)
  291. combinationActions := getCombinationActionsConf(advertiser)
  292. for _, combAction := range combinationActions {
  293. adActionDatas := make([]AdAction, 0, 20)
  294. percentBegin := combAction.PercentBegin
  295. percentEnd := combAction.PercentEnd
  296. actionGroup := combAction.GroupValue
  297. for _, action := range actionGroup {
  298. urls := make([]string, 0, 50)
  299. if dsp.ReqSource == "mh" {
  300. if action == "CLOSE" {
  301. action = "VIDEO_FINISH"
  302. }
  303. }
  304. switch action {
  305. case "VIEW":
  306. urls = showUrls
  307. case "CLICK":
  308. urls = clickUrls
  309. case "CLOSE":
  310. urls = closeUrls
  311. case "VIDEO_FINISH":
  312. urls = videoFinishUrls
  313. case "VIDEO_TIMER":
  314. urls = videoTimerUrls
  315. default:
  316. continue
  317. }
  318. // click的控制 控制bom
  319. if action == "CLICK" && dsp.RealReqSource == "bom" && dsp.SupClickFlag == 0 {
  320. continue
  321. }
  322. // show的控制 控制bom
  323. if action == "VIEW" && dsp.RealReqSource == "bom" && dsp.SupShowFlag == 0 {
  324. continue
  325. }
  326. if action == "CLICK" && !needClick {
  327. continue
  328. }
  329. if len(urls) == 0 && action == "VIDEO_TIMER" {
  330. continue
  331. }
  332. adActionData, err := genAdsAction(urls, advertiser, dsp, action, true)
  333. if err != nil {
  334. fmt.Printf("gen ads action data failed, err: %s\n", err)
  335. continue
  336. }
  337. // 没有url的就不要下发了
  338. if len(adActionData.Urls) == 0 {
  339. continue
  340. }
  341. adActionDatas = append(adActionDatas, *adActionData)
  342. }
  343. minValue := 2
  344. if len(videoTimerUrls) != 0 {
  345. minValue = 3
  346. }
  347. // 大于minValue才进行投放
  348. if len(adActionDatas) >= minValue {
  349. adInfo := AdInfo{
  350. AdActions: adActionDatas,
  351. PercentBegin: percentBegin,
  352. PercentEnd: percentEnd,
  353. }
  354. lastInfos = append(lastInfos, adInfo)
  355. }
  356. }
  357. targetUrl := ""
  358. if len(gotoUrls) != 0 {
  359. targetUrl = gotoUrls[0]
  360. }
  361. videoUrl := ""
  362. if len(videoUrls) != 0 {
  363. videoUrl = videoUrls[0]
  364. }
  365. randAdData := make([]AdAction, 0, 50)
  366. if len(lastInfos) != 0 {
  367. randIdx := rand.Intn(len(lastInfos))
  368. randAdData = lastInfos[randIdx].AdActions
  369. }
  370. hasClickAction := false
  371. for _, adData := range randAdData {
  372. if adData.Type == "CLICK" {
  373. hasClickAction = true
  374. break
  375. }
  376. }
  377. if !hasClickAction {
  378. targetUrl = ""
  379. }
  380. // 重新组装duration
  381. videoTimerUrls = make([]string, 0, 100)
  382. if len(randAdData) >= 3 {
  383. if randAdData[1].Type == "VIDEO_TIMER" {
  384. videoTimerUrls = randAdData[1].Urls
  385. }
  386. }
  387. rspAdDatas := make([]AdAction, 0, 20)
  388. for _, adData := range randAdData {
  389. if len(adData.Urls) == 0 || adData.Type == "" {
  390. continue
  391. }
  392. if adData.Type == "VIDEO_TIMER" && len(videoTimerUrls) > 0 {
  393. adData.Duration = int(dsp.AllDuration) - dsp.VideoTimeDuration
  394. } else if adData.Type == "VIDEO_TIMER" && len(videoTimerUrls) == 0 {
  395. adData.Duration = dsp.VideoTimeDuration
  396. } else if adData.Type == "VIEW" {
  397. if len(videoTimerUrls) > 0 {
  398. adData.Duration = dsp.VideoTimeDuration
  399. } else {
  400. adData.Duration = int(dsp.AllDuration)
  401. }
  402. }
  403. if adData.Type != "VIEW" {
  404. redis_data.SetDistributeActionNum(advertiser, adData.Type, dsp.SendPhoneType)
  405. }
  406. canReport, err := redis_data.GetDeviceIpReport(dsp.Imei, dsp.Ip)
  407. if err != nil {
  408. log.WithField("request_id", dsp.RequestId).Errorf("get device ip report failed: %s", err)
  409. return nil, err
  410. }
  411. md5Imei := ""
  412. // 返回的曝光, 如果没有返回过秒针的,那么加入
  413. if adData.Type == "VIEW" && canReport {
  414. if dsp.ReplaceFlag == 0 {
  415. md5Imei = utils.Md5(dsp.Imei)
  416. } else {
  417. md5Imei = dsp.Imei
  418. }
  419. conf := adslib.GetConf()
  420. adDataUrl := strings.ReplaceAll(conf.HostMiao, "__IMEI__", md5Imei)
  421. adData.Urls = append(adData.Urls, adDataUrl)
  422. redis_data.SetDeviceIpReport(dsp.Imei, dsp.Ip)
  423. }
  424. rspAdDatas = append(rspAdDatas, adData)
  425. }
  426. adData := AdData{
  427. TargetAddition: rspAdDatas,
  428. Target: targetUrl,
  429. Duration: dsp.AllDuration,
  430. VideoUrl: videoUrl,
  431. }
  432. return &adData, nil
  433. }
  434. // 组装展示
  435. func genAdsAction(urls []string, advertiser string,
  436. dsp *utils.DspParam, action string, needControl bool) (*AdAction, error) {
  437. // 获取advertiser上报的总量
  438. allSendNum, err := redis_data.GetAdsRequestNum(advertiser, dsp.SendPhoneType)
  439. if err != nil {
  440. return nil, err
  441. }
  442. allShowNum, err := redis_data.GetAdsFeedbackNum(advertiser, action, dsp.SendPhoneType)
  443. if err != nil {
  444. return nil, err
  445. }
  446. flowControlConf := redis_data.GetFlowPercentDuration(advertiser, action)
  447. flowPercent := 0
  448. duration := 0
  449. if flowControlConf != nil {
  450. flowPercent = flowControlConf.Percent
  451. duration = flowControlConf.Duration
  452. }
  453. lastUrls := make([]string, 0, 20)
  454. if !needControl || allSendNum == 0 || int(
  455. float32(allShowNum)/float32(allSendNum)*100) < flowPercent {
  456. reportUrl := getReportUrl(action, dsp)
  457. lastUrls = append(urls, reportUrl)
  458. }
  459. log.WithField("request_id", dsp.RequestId).Tracef("action: %s, all send: %d, all show: %d, control: +%v %+v %t\n", action, allSendNum, allShowNum, flowControlConf, lastUrls, needControl)
  460. if len(lastUrls) == 0 {
  461. duration = 0
  462. }
  463. if action == "VIDEO_TIMER" {
  464. duration = 7
  465. }
  466. adAction := AdAction{
  467. Type: action,
  468. Duration: duration,
  469. Urls: lastUrls,
  470. }
  471. return &adAction, nil
  472. }
  473. // 组装上报的url
  474. func getReportUrl(action string, dsp *utils.DspParam) string {
  475. urlHost := adslib.GetConf().HostIos
  476. reportUrl := fmt.Sprintf("%s?action=%s&advertiser=video&req_source=%s&brand=%s&city_code=%d&request_id=%s&spefial_flag=%d",
  477. urlHost, action, dsp.ReqSource, dsp.Brand, dsp.DspCityCode, dsp.RequestId, dsp.SendPhoneType)
  478. return reportUrl
  479. }