user.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. package v1
  2. import (
  3. "context"
  4. "designs/app/common/request"
  5. "designs/app/common/response"
  6. "designs/config"
  7. "designs/global"
  8. "designs/model"
  9. "designs/utils"
  10. "encoding/json"
  11. "fmt"
  12. "github.com/gin-gonic/gin"
  13. "github.com/pkg/errors"
  14. "go.mongodb.org/mongo-driver/v2/bson"
  15. "strconv"
  16. "strings"
  17. "time"
  18. )
  19. func ReceiveGameMsg(c *gin.Context) {
  20. //response.Success(c, gin.H{})
  21. //return
  22. form := request.Check(c, &struct {
  23. //Gid string `form:"gid" json:"gid" binding:"required"`
  24. //Pf string `form:"pf" json:"pf" binding:"required"`
  25. UserId int `form:"userId" json:"userId" binding:"required"`
  26. Action string `form:"action" json:"action" binding:"required"`
  27. Timestamp int64 `form:"timestamp" json:"timestamp" binding:"required"`
  28. Data string `form:"data" json:"data" binding:""`
  29. AdsId string `form:"adsId" json:"adsId" binding:""`
  30. AdsType string `form:"adsType" json:"adsType" binding:""`
  31. AdsScene string `form:"adsScene" json:"adsScene" binding:""`
  32. AdsState int `form:"adsState" json:"adsState" binding:""`
  33. AdStartTime int64 `form:"adStartTime" json:"adStartTime" binding:""`
  34. }{})
  35. gid := c.GetString("gid")
  36. pf := c.GetString("pf")
  37. openId := c.GetString("openid")
  38. if gid == "linkup" {
  39. global.App.Log.Info("用户请求ReceiveGameMsg,参数打印:")
  40. utils.PrintStructFields(form)
  41. }
  42. now := time.UnixMilli(form.Timestamp)
  43. var adStartTime time.Time
  44. if form.AdStartTime > 0 {
  45. adStartTime = time.UnixMilli(form.AdStartTime)
  46. }
  47. var err error
  48. if form.Action == "login" {
  49. //登录
  50. err = login(gid, pf, openId, form.UserId, now)
  51. //调用接口,上传留存
  52. CheckRetention(gid, pf, openId)
  53. } else if form.Action == "online" {
  54. //活跃
  55. err = online(gid, pf, openId, form.UserId, now)
  56. } else if form.Action == "offline" {
  57. //断开
  58. err = offline(gid, pf, openId, form.UserId, now)
  59. } else if form.Action == "seeAds" {
  60. //观看广告
  61. err = seeAds(gid, pf, openId, form.UserId, now, form.AdsId, form.AdsType, form.AdsScene, form.AdsState, adStartTime)
  62. } else {
  63. //自定义类型
  64. //查询有无对应的行为记录
  65. err = action(gid, pf, form.Action, form.UserId, now, form.Data)
  66. }
  67. //调用接口,检测需不需要上传到巨量
  68. CheckUserActive(gid, pf, openId)
  69. if err != nil {
  70. response.Fail(c, 1003, err.Error())
  71. return
  72. }
  73. response.Success(c, gin.H{})
  74. }
  75. func action(gid string, pf string, gameActionId string, userId int, now time.Time, option string) error {
  76. //fmt.Print(gameActionId)
  77. var gameAction model.GameAction
  78. err := global.App.DB.Table("game_action").
  79. Where("gid", gid).
  80. Where("actionId", gameActionId).
  81. First(&gameAction).Error
  82. if err != nil {
  83. return errors.New("该行为记录不存在")
  84. }
  85. if gameAction.Status == 0 {
  86. return errors.New("该行为记录未启用")
  87. }
  88. var userActionOption []model.UserActionOption
  89. if option != "" {
  90. optionMap := make(map[string]interface{})
  91. err = json.Unmarshal([]byte(option), &optionMap)
  92. if err != nil {
  93. return errors.New("选项解析错误")
  94. }
  95. for k, v := range optionMap {
  96. userActionOption = append(userActionOption, model.UserActionOption{
  97. OptionId: k,
  98. Value: fmt.Sprintf("%v", v),
  99. CreatedAt: model.XTime{
  100. Time: now,
  101. },
  102. })
  103. }
  104. }
  105. userAction := model.UserAction{
  106. UserId: userId,
  107. Gid: gid,
  108. Pf: pf,
  109. ActionId: gameActionId,
  110. CreatedAt: model.XTime{Time: now},
  111. }
  112. err = global.App.DB.Transaction(func(tx *utils.WtDB) error {
  113. err := tx.Table("user_action").Create(&userAction).Error
  114. if err != nil {
  115. return err
  116. }
  117. if len(userActionOption) > 0 {
  118. for _, option := range userActionOption {
  119. option.UserActionId = userAction.ID
  120. err = tx.Table("user_action_option").Create(&option).Error
  121. if err != nil {
  122. return err
  123. }
  124. }
  125. }
  126. return nil
  127. })
  128. if err != nil {
  129. return err
  130. }
  131. return nil
  132. }
  133. func login(gid string, pf string, openId string, userId int, now time.Time) error {
  134. var user model.User
  135. err := global.App.DB.Table("user").Where("gid", gid).Where("pf", pf).Where("userId", userId).First(&user).Error
  136. if user.ID == 0 {
  137. //没有用户,需要新增
  138. user.UserId = userId
  139. user.Gid = gid
  140. user.Pf = pf
  141. user.CreatedAt = now
  142. user.OpenId = openId
  143. err = global.App.DB.Table("user").Create(&user).Error
  144. if err != nil {
  145. global.App.Log.Error("创建用户失败", err.Error(), user)
  146. return err
  147. }
  148. }
  149. userLogin := model.UserLogin{
  150. Gid: gid,
  151. Pf: pf,
  152. UserId: userId,
  153. LoginTime: now,
  154. }
  155. err = global.App.DB.Table("user_login").Create(&userLogin).Error
  156. if err != nil {
  157. global.App.Log.Error("存储用户登录信息失败", err.Error(), user)
  158. return err
  159. }
  160. userOnline := model.UserOnline{
  161. Gid: gid,
  162. Pf: pf,
  163. UserId: userId,
  164. LogTime: now,
  165. Date: now.Format("20060102"),
  166. Type: 1,
  167. }
  168. err = global.App.DB.Table("user_online").Create(&userOnline).Error
  169. if err != nil {
  170. global.App.Log.Error("存储用户活跃信息失败", err.Error(), userOnline)
  171. return err
  172. }
  173. err = CreateUserBehavior(gid, pf, openId, now)
  174. if err != nil {
  175. global.App.Log.Error("存储用户信息进入mongo失败", err.Error(), userOnline)
  176. }
  177. return nil
  178. }
  179. func online(gid string, pf string, openId string, userId int, now time.Time) error {
  180. userOnline := model.UserOnline{
  181. Gid: gid,
  182. Pf: pf,
  183. UserId: userId,
  184. LogTime: now,
  185. Date: now.Format("20060102"),
  186. Type: 1,
  187. }
  188. err := global.App.DB.Table("user_online").Create(&userOnline).Error
  189. if err != nil {
  190. global.App.Log.Error("存储用户活跃信息失败", err.Error(), userOnline)
  191. return err
  192. }
  193. err = UpdateUserBehaviorDuration(gid, pf, openId, now, 1)
  194. if err != nil {
  195. global.App.Log.Error("存储用户在线时长mongo失败", err.Error(), userOnline)
  196. }
  197. return nil
  198. }
  199. func offline(gid string, pf string, openId string, userId int, now time.Time) error {
  200. userOnline := model.UserOnline{
  201. Gid: gid,
  202. Pf: pf,
  203. UserId: userId,
  204. LogTime: now,
  205. Date: now.Format("20060102"),
  206. Type: 2,
  207. }
  208. err := global.App.DB.Table("user_online").Create(&userOnline).Error
  209. if err != nil {
  210. global.App.Log.Error("存储用户活跃信息失败", err.Error(), userOnline)
  211. return err
  212. }
  213. err = UpdateUserBehaviorDuration(gid, pf, openId, now, 2)
  214. if err != nil {
  215. global.App.Log.Error("存储用户在线时长mongo失败", err.Error(), userOnline)
  216. }
  217. return nil
  218. }
  219. func seeAds(gid string, pf string, openId string, userId int, now time.Time, AdsId string, AdsType string, AdsScene string, AdsState int, adStartTime time.Time) error {
  220. if AdsId == "" || AdsType == "" || AdsScene == "" {
  221. return errors.New("参数缺失")
  222. }
  223. userOnline := model.UserSeeAds{
  224. Gid: gid,
  225. Pf: pf,
  226. UserId: userId,
  227. CreatedAt: now,
  228. Date: now.Format("20060102"),
  229. AdsId: AdsId,
  230. AdsType: AdsType,
  231. AdsState: AdsState,
  232. AdsScene: AdsScene,
  233. StartTime: adStartTime,
  234. }
  235. err := global.App.DB.Table("user_see_ads").Create(&userOnline).Error
  236. if err != nil {
  237. global.App.Log.Error("存储用户活跃信息失败", err.Error(), userOnline)
  238. return err
  239. }
  240. err = UpdateUserBehaviorAdInfo(gid, pf, openId, AdsState)
  241. if err != nil {
  242. global.App.Log.Error("存储用户观看广告mongo失败", err.Error(), userOnline)
  243. }
  244. return nil
  245. }
  246. func InitUser(c *gin.Context) {
  247. gidKey := config.Get("app.gid") + "*"
  248. keys, _ := global.App.Redis.Keys(context.Background(), gidKey).Result()
  249. for _, key := range keys {
  250. gid := strings.Split(key, ":")[1]
  251. userKeyWeb := gid + ":" + "web" + ":" + config.Get("app.user_table_key") + "*"
  252. userKeyTt := gid + ":" + "tt" + ":" + config.Get("app.user_table_key") + "*"
  253. userKeyWx := gid + ":" + "wx" + ":" + config.Get("app.user_table_key") + "*"
  254. webKey, _ := global.App.Redis.Keys(context.Background(), userKeyWeb).Result()
  255. for _, v := range webKey {
  256. res, err2 := global.App.Redis.HGetAll(context.Background(), v).Result()
  257. if err2 != nil {
  258. continue
  259. }
  260. userId, _ := strconv.Atoi(res["userId"])
  261. registerTimeUnix, _ := strconv.Atoi(res["registerTime"])
  262. registerTime := time.Unix(int64(registerTimeUnix), 0)
  263. global.App.DB.Table("user").Create(&model.User{
  264. Gid: res["gid"],
  265. Pf: res["pf"],
  266. UserId: userId,
  267. CreatedAt: registerTime,
  268. })
  269. }
  270. ttKey, _ := global.App.Redis.Keys(context.Background(), userKeyTt).Result()
  271. for _, v := range ttKey {
  272. res, err2 := global.App.Redis.HGetAll(context.Background(), v).Result()
  273. if err2 != nil {
  274. continue
  275. }
  276. userId, _ := strconv.Atoi(res["userId"])
  277. registerTimeUnix, _ := strconv.Atoi(res["registerTime"])
  278. registerTime := time.Unix(int64(registerTimeUnix), 0)
  279. global.App.DB.Table("user").Create(&model.User{
  280. Gid: res["gid"],
  281. Pf: res["pf"],
  282. UserId: userId,
  283. CreatedAt: registerTime,
  284. })
  285. }
  286. wxKey, _ := global.App.Redis.Keys(context.Background(), userKeyWx).Result()
  287. for _, v := range wxKey {
  288. res, err2 := global.App.Redis.HGetAll(context.Background(), v).Result()
  289. if err2 != nil {
  290. continue
  291. }
  292. userId, _ := strconv.Atoi(res["userId"])
  293. registerTimeUnix, _ := strconv.Atoi(res["registerTime"])
  294. registerTime := time.Unix(int64(registerTimeUnix), 0)
  295. global.App.DB.Table("user").Create(&model.User{
  296. Gid: res["gid"],
  297. Pf: res["pf"],
  298. UserId: userId,
  299. CreatedAt: registerTime,
  300. })
  301. }
  302. }
  303. response.Success(c, gin.H{"data": "success"})
  304. }
  305. func ReceiveAdsInfo(c *gin.Context) {
  306. //response.Success(c, gin.H{"data": "success"})
  307. //return
  308. form := request.Check(c, &struct {
  309. Aid string `form:"aid" json:"aid" binding:""`
  310. Pid string `form:"pid" json:"pid" binding:""`
  311. Cid string `form:"cid" json:"cid" binding:""`
  312. }{})
  313. //存储参数
  314. global.App.Log.Info("ReceiveAdsInfo", form)
  315. gid := c.GetString("gid")
  316. pf := c.GetString("pf")
  317. openId := c.GetString("openid")
  318. userId := gid + "|" + pf + "|" + openId
  319. global.App.Log.Info("userId", userId)
  320. id := userId + "|" + form.Aid
  321. aid, _ := strconv.Atoi(form.Aid)
  322. pid, _ := strconv.Atoi(form.Pid)
  323. collection := global.App.MongoDB.Database("chunhao").Collection("adRelated")
  324. var adRelated model.AdRelated
  325. filter := bson.M{"_id": id}
  326. collection.FindOne(context.Background(), filter).Decode(&adRelated)
  327. if adRelated.Id == "" {
  328. //新增
  329. adData := model.AdRelated{
  330. UserId: userId,
  331. Id: id,
  332. Aid: int64(aid),
  333. Pid: int64(pid),
  334. Cid: form.Cid,
  335. Duration: 0,
  336. StartNum: 1,
  337. Revenue: 0,
  338. ReqCount: 0,
  339. ExpCount: 0,
  340. CreateTime: time.Now().Unix(),
  341. }
  342. //更新到MongoDB 中
  343. _, err := collection.InsertOne(context.Background(), adData)
  344. if err != nil {
  345. response.Fail(c, 1003, "写入数据失败"+err.Error())
  346. return
  347. }
  348. }
  349. ////关联到userInfo 上
  350. //filter = bson.M{"_id": userId}
  351. //update := bson.M{
  352. // "$set": struct {
  353. // RelatedAid int64 `bson:"relatedAid" json:"relatedAid"`
  354. // }{
  355. // RelatedAid: int64(aid),
  356. // },
  357. //}
  358. //collection = global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  359. //_, err := collection.UpdateOne(context.Background(), filter, update)
  360. //if err != nil {
  361. // response.Fail(c, 1003, err.Error())
  362. // return
  363. //}
  364. response.Success(c, gin.H{"data": "success"})
  365. }