xiaomi.go 14 KB

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