behavior.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. package v1
  2. import (
  3. "context"
  4. "designs/app/common/response"
  5. "designs/config"
  6. "designs/global"
  7. "designs/model"
  8. "designs/service"
  9. "encoding/json"
  10. "errors"
  11. "fmt"
  12. "github.com/gin-gonic/gin"
  13. "go.mongodb.org/mongo-driver/v2/bson"
  14. "strconv"
  15. "time"
  16. )
  17. //func ReceiveUserBehavior(c *gin.Context) {
  18. // form := request.Check(c, &struct {
  19. // Gid string `form:"gid" json:"gid" binding:"required"`
  20. // Pf string `form:"pf" json:"pf" binding:"required"`
  21. // OpenId string `form:"openId" json:"openId" binding:"required"`
  22. // AdData interface{} `form:"adData" json:"adData" binding:""`
  23. // AdFromCount int `form:"adFromCount" json:"adFromCount" binding:""`
  24. // TotalDuration int `form:"totalDuration" json:"totalDuration" binding:""`
  25. // TotalAdReqCount int `form:"totalAdReqCount" json:"totalAdReqCount" binding:""`
  26. // TotalAdEposedCount int `form:"totalAdEposedCount" json:"totalAdEposedCount" binding:""`
  27. // }{})
  28. //
  29. // //if form.AdData != nil {
  30. // // var AdData map[string]interface{}
  31. // //}
  32. // behavior := UserBehavior{
  33. // Id: form.Gid + "|" + form.Pf + "|" + form.OpenId,
  34. // Gid: form.Gid,
  35. // Pf: form.Pf,
  36. // OpenId: form.OpenId,
  37. // AdData: form.AdData,
  38. // AdFromCount: form.AdFromCount,
  39. // TotalDuration: form.TotalDuration,
  40. // TotalAdReqCount: form.TotalAdReqCount,
  41. // TotalAdEposedCount: form.TotalAdEposedCount,
  42. // }
  43. //
  44. // collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  45. //
  46. // filter := bson.M{"_id": behavior.Id}
  47. // result := make(map[string]interface{})
  48. // err := collection.FindOne(context.Background(), filter).Decode(&result)
  49. //
  50. // if len(result) == 0 {
  51. // //新增
  52. // _, err = collection.InsertOne(context.Background(), behavior)
  53. // if err != nil {
  54. // response.Fail(c, 1003, "写入数据失败"+err.Error())
  55. // return
  56. // }
  57. // } else {
  58. // var newAdData AdData
  59. // adData, _ := json.Marshal(form.AdData)
  60. // json.Unmarshal(adData, &newAdData)
  61. //
  62. // var oldAdData AdData
  63. // oldAdDatas, _ := json.Marshal(result["adData"])
  64. // json.Unmarshal(oldAdDatas, &oldAdData)
  65. //
  66. // newAdData.Reported = oldAdData.Reported
  67. //
  68. // //更新到MongoDB 中
  69. // update := bson.M{
  70. // "$set": struct {
  71. // Gid string `bson:"gid" json:"gid"`
  72. // Pf string `bson:"pf" json:"pf"`
  73. // OpenId string `bson:"openId" json:"openId"`
  74. // AdData interface{} `bson:"adData" json:"adData"`
  75. // AdFromCount int `bson:"adFromCount" json:"adFromCount"`
  76. // TotalDuration int `bson:"totalDuration" json:"totalDuration"`
  77. // TotalAdReqCount int `bson:"totalAdReqCount" json:"totalAdReqCount"`
  78. // TotalAdEposedCount int `bson:"totalAdEposedCount" json:"totalAdEposedCount"`
  79. // }{
  80. // Gid: behavior.Gid,
  81. // Pf: behavior.Pf,
  82. // OpenId: behavior.OpenId,
  83. // AdData: newAdData,
  84. // AdFromCount: behavior.AdFromCount,
  85. // TotalDuration: behavior.TotalDuration,
  86. // TotalAdReqCount: behavior.TotalAdReqCount,
  87. // TotalAdEposedCount: behavior.TotalAdEposedCount,
  88. // },
  89. // }
  90. // _, err = collection.UpdateOne(context.Background(), filter, update)
  91. // if err != nil {
  92. // response.Fail(c, 1003, "写入数据失败"+err.Error())
  93. // return
  94. // }
  95. // }
  96. //
  97. // //如果是从广告获取进来的用户,则需要检测是否上传
  98. // if form.AdData != nil {
  99. // res := service.OceanReportAction(behavior.Id)
  100. // if res.Code != 0 {
  101. // //上传出现了问题,或者并没有上传
  102. // global.App.Log.Error(res.Code, res.Message)
  103. // }
  104. // }
  105. //
  106. // response.Success(c, gin.H{})
  107. //}
  108. func CheckUserBehavior(c *gin.Context) {
  109. //response.Success(c, gin.H{"data": "success"})
  110. //return
  111. gid := c.GetString("gid")
  112. pf := c.GetString("pf")
  113. openId := c.GetString("openid")
  114. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  115. //
  116. filter := bson.M{"_id": gid + "|" + pf + "|" + openId}
  117. result := make(map[string]interface{})
  118. collection.FindOne(context.Background(), filter).Decode(&result)
  119. if len(result) == 0 {
  120. response.Success(c, gin.H{
  121. "data": nil,
  122. })
  123. } else {
  124. response.Success(c, gin.H{
  125. "data": result,
  126. })
  127. }
  128. }
  129. func UpdateUserBehavior(c *gin.Context) {
  130. //查出所有需要更新的数据
  131. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  132. filters := bson.M{}
  133. filters["adData"] = bson.M{"$exists": true}
  134. var result []map[string]interface{}
  135. cur, err := collection.Find(context.Background(), filters)
  136. if err != nil {
  137. response.Fail(c, 1001, err.Error())
  138. }
  139. err = cur.All(context.Background(), &result)
  140. if err != nil {
  141. response.Fail(c, 1001, err.Error())
  142. return
  143. }
  144. for _, v := range result {
  145. var adData map[string]interface{}
  146. oldAdDatas, _ := json.Marshal(v["adData"])
  147. json.Unmarshal(oldAdDatas, &adData)
  148. if adData["createtime"] != nil {
  149. //错误数据,需要修正
  150. filter := bson.M{"_id": v["_id"]}
  151. //
  152. adData["createTime"] = adData["createtime"]
  153. adData["adReqCount"] = adData["adreqcount"]
  154. adData["adEposedcount"] = adData["adeposedcount"]
  155. adData["reportUrl"] = adData["reporturl"]
  156. delete(adData, "createtime")
  157. delete(adData, "adreqcount")
  158. delete(adData, "adeposedcount")
  159. delete(adData, "reporturl")
  160. //更新到MongoDB 中
  161. update := bson.M{
  162. "$set": struct {
  163. AdData map[string]interface{} `bson:"adData" json:"adData"`
  164. }{
  165. AdData: adData,
  166. },
  167. }
  168. _, err = collection.UpdateOne(context.Background(), filter, update)
  169. if err != nil {
  170. response.Fail(c, 1003, "写入数据失败"+err.Error())
  171. return
  172. }
  173. }
  174. }
  175. defer cur.Close(context.Background())
  176. //更新成正确的数据
  177. response.Success(c, gin.H{
  178. "data": result,
  179. })
  180. }
  181. func FindUserBehavior(id string) *model.UserBehavior {
  182. filter := bson.M{"_id": id}
  183. var result model.UserBehavior
  184. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  185. err := collection.FindOne(context.Background(), filter).Decode(&result)
  186. if err != nil {
  187. return nil
  188. }
  189. return &result
  190. }
  191. // 新建UserBehavior
  192. func CreateUserBehavior(gid string, pf string, openId string, now time.Time) error {
  193. //id := gid + "|" + pf + "|" + openId
  194. //
  195. //Behavior := FindUserBehavior(id)
  196. //if Behavior != nil {
  197. // //更新start_num参数
  198. // collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  199. // filter := bson.M{"_id": id}
  200. // update := bson.M{"$inc": bson.M{"startNum": 1}}
  201. //
  202. // _, err := collection.UpdateOne(context.Background(), filter, update)
  203. // if err != nil {
  204. // return err
  205. // }
  206. //
  207. // //更新关联的广告数据
  208. // filter = bson.M{"userId": id}
  209. // collection = global.App.MongoDB.Database("chunhao").Collection("adRelated")
  210. // update = bson.M{"$inc": bson.M{"startNum": 1}}
  211. // _, err = collection.UpdateMany(context.Background(), filter, update)
  212. // if err != nil {
  213. // return err
  214. // }
  215. //
  216. // return nil
  217. //} else {
  218. // behavior := model.UserBehavior{
  219. // Id: id,
  220. // Gid: gid,
  221. // Pf: pf,
  222. // OpenId: openId,
  223. // TotalDuration: 0,
  224. // TotalAdReqCount: 0,
  225. // TotalAdEposedCount: 0,
  226. // RelatedAid: 0,
  227. // StartNum: 1,
  228. // CreateTime: int(now.Unix()),
  229. // CreateDate: now.Format("20060102"),
  230. // ActiveStatus: false,
  231. // ConversionStatus: false,
  232. // RemainData: nil,
  233. // }
  234. // //新增
  235. // collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  236. // _, err := collection.InsertOne(context.Background(), behavior)
  237. // if err != nil {
  238. // return err
  239. // }
  240. //}
  241. ////存储在线数据到redis中
  242. //global.App.Redis.Set(context.Background(), id+"|online", now.Unix(), time.Second*300)
  243. return nil
  244. }
  245. // 更新UserBehavior 在线时间
  246. func UpdateUserBehaviorDuration(gid string, pf string, openId string, now time.Time, types int) error {
  247. id := gid + "|" + pf + "|" + openId
  248. fmt.Println(now.Format("2006-01-02 15:04:05"))
  249. Behavior := FindUserBehavior(id)
  250. if Behavior == nil {
  251. return errors.New("该用户数据未保存,无法计算在线时间")
  252. }
  253. lastTime, _ := global.App.Redis.Get(context.Background(), id+"|online").Result()
  254. //当状态为在线时,刷新redis数据,状态为2是离线,不刷新
  255. if types == 1 {
  256. global.App.Redis.Set(context.Background(), id+"|online", now.Unix(), time.Second*300)
  257. } else {
  258. global.App.Redis.Del(context.Background(), id+"|online")
  259. }
  260. //fmt.Println("types", types)
  261. //如果redis中没有查到在线状态,那就视为刚刚登录,不增加时间
  262. if lastTime == "" {
  263. return nil
  264. }
  265. //计算时间差
  266. lastTimeUnix, _ := strconv.ParseInt(lastTime, 10, 64)
  267. duration := now.Unix() - lastTimeUnix
  268. //更新到MongoDB 中
  269. update := bson.M{
  270. "$set": struct {
  271. TotalDuration int `bson:"totalDuration" json:"totalDuration"`
  272. }{
  273. TotalDuration: Behavior.TotalDuration + int(duration),
  274. },
  275. }
  276. filter := bson.M{"_id": id}
  277. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  278. _, err := collection.UpdateOne(context.Background(), filter, update)
  279. if err != nil {
  280. return err
  281. }
  282. //更新到当日数据中 todo
  283. //更新到广告关联数据中
  284. filter = bson.M{"userId": id}
  285. collection = global.App.MongoDB.Database("chunhao").Collection("adRelated")
  286. update = bson.M{"$inc": bson.M{"duration": int(duration)}}
  287. _, err = collection.UpdateMany(context.Background(), filter, update)
  288. if err != nil {
  289. return err
  290. }
  291. return nil
  292. }
  293. // 更新UserBehavior 看广告的数据
  294. func UpdateUserBehaviorAdInfo(gid string, pf string, openId string, adsState int) error {
  295. id := gid + "|" + pf + "|" + openId
  296. collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  297. filter := bson.M{"_id": id}
  298. Behavior := FindUserBehavior(id)
  299. if Behavior == nil {
  300. return errors.New("该用户数据未保存,无法累加看广告数据")
  301. }
  302. var AdReqCount int
  303. var AdEposedcount int
  304. if adsState == 0 {
  305. //展示不成功
  306. } else if adsState == 1 {
  307. //展示成功
  308. AdReqCount = 1
  309. } else if adsState == 2 {
  310. //展示成功并且看完
  311. AdReqCount = 1
  312. AdEposedcount = 1
  313. }
  314. //更新到总数据中
  315. update := bson.M{
  316. "$set": struct {
  317. TotalAdReqCount int `bson:"totalAdReqCount" json:"totalAdReqCount"`
  318. TotalAdEposedCount int `bson:"totalAdEposedCount" json:"totalAdEposedCount"`
  319. }{
  320. TotalAdReqCount: Behavior.TotalAdReqCount + AdReqCount,
  321. TotalAdEposedCount: Behavior.TotalAdEposedCount + AdEposedcount,
  322. },
  323. }
  324. _, err := collection.UpdateOne(context.Background(), filter, update)
  325. if err != nil {
  326. return err
  327. }
  328. //更新到当日数据中 todo
  329. //更新到广告关联数据中
  330. filter = bson.M{"userId": id}
  331. collection = global.App.MongoDB.Database("chunhao").Collection("adRelated")
  332. update = bson.M{"$inc": bson.M{"req_count": AdReqCount, "exp_count": AdEposedcount}}
  333. _, err = collection.UpdateMany(context.Background(), filter, update)
  334. if err != nil {
  335. return err
  336. }
  337. return nil
  338. }
  339. // 上报给巨量对接系统
  340. func CheckUserActive(gid string, pf string, openId string) {
  341. request := map[string]interface{}{
  342. "gid": gid,
  343. "platform": pf,
  344. "openId": openId,
  345. }
  346. data, err := service.CurlPost(config.Get("app.check_user_active"), request, nil)
  347. if err != nil {
  348. global.App.Log.Error("CheckUserActive err: ", err)
  349. return
  350. }
  351. res := make(map[string]interface{})
  352. err = json.Unmarshal([]byte(data), &res)
  353. if err != nil {
  354. global.App.Log.Error("解析返回json错误: ", err)
  355. }
  356. fmt.Println(res)
  357. }
  358. type ReportReq struct {
  359. EventType string `json:"event_type"`
  360. Context *ReportContext `json:"context"`
  361. Properties map[string]interface{} `json:"properties,omitempty"`
  362. Timestamp int64 `json:"timestamp"`
  363. }
  364. type ReportContext struct {
  365. Ad *ReportContextAdCfg `json:"ad"` //信息流相关的信息
  366. Device map[string]interface{} `json:"device,omitempty"` //设备相关的信息
  367. }
  368. type ReportContextAdCfg struct {
  369. Callback string `json:"callback"`
  370. MatchType string `json:"match_type,omitempty"`
  371. }
  372. type HttpResult struct {
  373. Code int `bson:"code"`
  374. Msg string `bson:"msg"`
  375. }
  376. func OceanReport(evt string, cid string) bool {
  377. url := "https://analytics.oceanengine.com/api/v2/conversion"
  378. dat := &ReportReq{
  379. EventType: evt,
  380. Context: &ReportContext{Ad: &ReportContextAdCfg{Callback: cid}},
  381. Timestamp: time.Now().UnixMilli(),
  382. }
  383. var resp HttpResult
  384. data, err := service.CurlPost(url, dat, nil)
  385. if err != nil {
  386. return false
  387. }
  388. json.Unmarshal([]byte(data), &resp)
  389. if resp.Code == 0 {
  390. return true
  391. } else {
  392. return false
  393. }
  394. }
  395. func CheckRetention(gid string, pf string, openId string) {
  396. request := map[string]interface{}{
  397. "gid": gid,
  398. "platform": pf,
  399. "openId": openId,
  400. }
  401. data, err := service.CurlPost(config.Get("app.check_retention"), request, nil)
  402. if err != nil {
  403. global.App.Log.Error("CheckUserActive err: ", err)
  404. return
  405. }
  406. res := make(map[string]interface{})
  407. err = json.Unmarshal([]byte(data), &res)
  408. if err != nil {
  409. global.App.Log.Error("解析返回json错误: ", err)
  410. }
  411. }