xiaomi.go 14 KB

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