user.go 9.8 KB

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