user.go 11 KB

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