user.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. "os"
  16. "path/filepath"
  17. "strconv"
  18. "strings"
  19. "time"
  20. )
  21. func ReceiveGameMsg(c *gin.Context) {
  22. //response.Success(c, gin.H{})
  23. //return
  24. form := request.Check(c, &struct {
  25. //Gid string `form:"gid" json:"gid" binding:"required"`
  26. //Pf string `form:"pf" json:"pf" binding:"required"`
  27. UserId int `form:"userId" json:"userId" binding:"required"`
  28. Action string `form:"action" json:"action" binding:"required"`
  29. Timestamp int64 `form:"timestamp" json:"timestamp" binding:"required"`
  30. Data string `form:"data" json:"data" binding:""`
  31. AdsId string `form:"adsId" json:"adsId" binding:""`
  32. AdsType string `form:"adsType" json:"adsType" binding:""`
  33. AdsScene string `form:"adsScene" json:"adsScene" binding:""`
  34. AdsState int `form:"adsState" json:"adsState" binding:""`
  35. AdStartTime int64 `form:"adStartTime" json:"adStartTime" binding:""`
  36. }{})
  37. gid := c.GetString("gid")
  38. pf := c.GetString("pf")
  39. openId := c.GetString("openid")
  40. if gid == "zmybp_ds2" && form.Action == "seeAds" {
  41. // 生成日期目录路径(示例:./data/2024-06-15)
  42. now := time.Now()
  43. dateDir := now.Format("2006-01-02")
  44. dirPath := filepath.Join("storage", dateDir)
  45. // 创建日期目录(若不存在)
  46. os.MkdirAll(dirPath, 0755)
  47. // 生成文件名(示例:g123_wechat.txt)
  48. filePath := filepath.Join(dirPath, "adsLog.txt")
  49. // 追加写入文件
  50. file, _ := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
  51. defer file.Close()
  52. // 写入数据(示例:1584,oXyZ123456\n)
  53. if _, err := fmt.Fprintf(file, "%d,%s,%s,%s,%d,%s\n", form.UserId, form.AdsId, form.AdsScene, form.AdsType, form.AdsState, now.Format("2006-01-02 15:04:05")); err != nil {
  54. }
  55. }
  56. now := time.UnixMilli(form.Timestamp)
  57. var adStartTime time.Time
  58. if form.AdStartTime > 0 {
  59. adStartTime = time.UnixMilli(form.AdStartTime)
  60. }
  61. var err error
  62. if form.Action == "login" {
  63. //登录
  64. err = login(gid, pf, openId, form.UserId, now)
  65. //调用接口,上传留存
  66. CheckRetention(gid, pf, openId)
  67. } else if form.Action == "online" {
  68. //活跃
  69. err = online(gid, pf, openId, form.UserId, now)
  70. err = SetLocalActiveLog(gid, pf, openId, form.UserId, 1, now)
  71. } else if form.Action == "offline" {
  72. //断开
  73. err = offline(gid, pf, openId, form.UserId, now)
  74. err = SetLocalActiveLog(gid, pf, openId, form.UserId, 2, now)
  75. } else if form.Action == "seeAds" {
  76. //观看广告
  77. err = seeAds(gid, pf, openId, form.UserId, now, form.AdsId, form.AdsType, form.AdsScene, form.AdsState, adStartTime)
  78. } else {
  79. //自定义类型
  80. //查询有无对应的行为记录
  81. err = action(gid, pf, form.Action, form.UserId, now, form.Data)
  82. }
  83. //调用接口,检测需不需要上传到巨量
  84. CheckUserActive(gid, pf, openId)
  85. if err != nil {
  86. response.Fail(c, 1003, err.Error())
  87. return
  88. }
  89. response.Success(c, gin.H{})
  90. }
  91. func action(gid string, pf string, gameActionId string, userId int, now time.Time, option string) error {
  92. //fmt.Print(gameActionId)
  93. var gameAction model.GameAction
  94. err := global.App.DB.Table("game_action").
  95. Where("gid", gid).
  96. Where("actionId", gameActionId).
  97. First(&gameAction).Error
  98. if err != nil {
  99. return errors.New("该行为记录不存在")
  100. }
  101. if gameAction.Status == 0 {
  102. return errors.New("该行为记录未启用")
  103. }
  104. var userActionOption []model.UserActionOption
  105. if option != "" {
  106. optionMap := make(map[string]interface{})
  107. err = json.Unmarshal([]byte(option), &optionMap)
  108. if err != nil {
  109. return errors.New("选项解析错误")
  110. }
  111. for k, v := range optionMap {
  112. userActionOption = append(userActionOption, model.UserActionOption{
  113. OptionId: k,
  114. Value: fmt.Sprintf("%v", v),
  115. CreatedAt: model.XTime{
  116. Time: now,
  117. },
  118. })
  119. }
  120. }
  121. userAction := model.UserAction{
  122. UserId: userId,
  123. Gid: gid,
  124. Pf: pf,
  125. ActionId: gameActionId,
  126. CreatedAt: model.XTime{Time: now},
  127. }
  128. err = global.App.DB.Transaction(func(tx *utils.WtDB) error {
  129. err := tx.Table("user_action").Create(&userAction).Error
  130. if err != nil {
  131. return err
  132. }
  133. if len(userActionOption) > 0 {
  134. for _, option := range userActionOption {
  135. option.UserActionId = userAction.ID
  136. err = tx.Table("user_action_option").Create(&option).Error
  137. if err != nil {
  138. return err
  139. }
  140. }
  141. }
  142. return nil
  143. })
  144. if err != nil {
  145. return err
  146. }
  147. return nil
  148. }
  149. func login(gid string, pf string, openId string, userId int, now time.Time) error {
  150. var user model.User
  151. err := global.App.DB.Table("user").Where("gid", gid).Where("pf", pf).Where("userId", userId).First(&user).Error
  152. if user.ID == 0 {
  153. //没有用户,需要新增
  154. user.UserId = userId
  155. user.Gid = gid
  156. user.Pf = pf
  157. user.CreatedAt = now
  158. user.OpenId = openId
  159. err = global.App.DB.Table("user").Create(&user).Error
  160. if err != nil {
  161. global.App.Log.Error("创建用户失败", err.Error(), user)
  162. return err
  163. }
  164. }
  165. userLogin := model.UserLogin{
  166. Gid: gid,
  167. Pf: pf,
  168. UserId: userId,
  169. LoginTime: now,
  170. }
  171. err = global.App.DB.Table("user_login").Create(&userLogin).Error
  172. if err != nil {
  173. global.App.Log.Error("存储用户登录信息失败", err.Error(), user)
  174. return err
  175. }
  176. userOnline := model.UserOnline{
  177. Gid: gid,
  178. Pf: pf,
  179. UserId: userId,
  180. LogTime: now,
  181. Date: now.Format("20060102"),
  182. Type: 1,
  183. }
  184. err = global.App.DB.Table("user_online").Create(&userOnline).Error
  185. if err != nil {
  186. global.App.Log.Error("存储用户活跃信息失败", err.Error(), userOnline)
  187. return err
  188. }
  189. err = CreateUserBehavior(gid, pf, openId, now)
  190. if err != nil {
  191. global.App.Log.Error("存储用户信息进入mongo失败", err.Error(), userOnline)
  192. }
  193. return nil
  194. }
  195. func online(gid string, pf string, openId string, userId int, now time.Time) error {
  196. userOnline := model.UserOnline{
  197. Gid: gid,
  198. Pf: pf,
  199. UserId: userId,
  200. LogTime: now,
  201. Date: now.Format("20060102"),
  202. Type: 1,
  203. }
  204. err := global.App.DB.Table("user_online").Create(&userOnline).Error
  205. if err != nil {
  206. global.App.Log.Error("存储用户活跃信息失败", err.Error(), userOnline)
  207. return err
  208. }
  209. err = UpdateUserBehaviorDuration(gid, pf, openId, now, 1)
  210. if err != nil {
  211. global.App.Log.Error("存储用户在线时长mongo失败", err.Error(), userOnline)
  212. }
  213. return nil
  214. }
  215. func offline(gid string, pf string, openId string, userId int, now time.Time) error {
  216. userOnline := model.UserOnline{
  217. Gid: gid,
  218. Pf: pf,
  219. UserId: userId,
  220. LogTime: now,
  221. Date: now.Format("20060102"),
  222. Type: 2,
  223. }
  224. err := global.App.DB.Table("user_online").Create(&userOnline).Error
  225. if err != nil {
  226. global.App.Log.Error("存储用户活跃信息失败", err.Error(), userOnline)
  227. return err
  228. }
  229. err = UpdateUserBehaviorDuration(gid, pf, openId, now, 2)
  230. if err != nil {
  231. global.App.Log.Error("存储用户在线时长mongo失败", err.Error(), userOnline)
  232. }
  233. return nil
  234. }
  235. 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 {
  236. if AdsId == "" || AdsType == "" || AdsScene == "" {
  237. return errors.New("参数缺失")
  238. }
  239. userOnline := model.UserSeeAds{
  240. Gid: gid,
  241. Pf: pf,
  242. UserId: userId,
  243. CreatedAt: now,
  244. Date: now.Format("20060102"),
  245. AdsId: AdsId,
  246. AdsType: AdsType,
  247. AdsState: AdsState,
  248. AdsScene: AdsScene,
  249. StartTime: adStartTime,
  250. }
  251. err := global.App.DB.Table("user_see_ads").Create(&userOnline).Error
  252. if err != nil {
  253. global.App.Log.Error("存储用户活跃信息失败", err.Error(), userOnline)
  254. return err
  255. }
  256. err = UpdateUserBehaviorAdInfo(gid, pf, openId, AdsState)
  257. if err != nil {
  258. global.App.Log.Error("存储用户观看广告mongo失败", err.Error(), userOnline)
  259. }
  260. return nil
  261. }
  262. func InitUser(c *gin.Context) {
  263. gidKey := config.Get("app.gid") + "*"
  264. keys, _ := global.App.Redis.Keys(context.Background(), gidKey).Result()
  265. for _, key := range keys {
  266. gid := strings.Split(key, ":")[1]
  267. userKeyWeb := gid + ":" + "web" + ":" + config.Get("app.user_table_key") + "*"
  268. userKeyTt := gid + ":" + "tt" + ":" + config.Get("app.user_table_key") + "*"
  269. userKeyWx := gid + ":" + "wx" + ":" + config.Get("app.user_table_key") + "*"
  270. webKey, _ := global.App.Redis.Keys(context.Background(), userKeyWeb).Result()
  271. for _, v := range webKey {
  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. ttKey, _ := global.App.Redis.Keys(context.Background(), userKeyTt).Result()
  287. for _, v := range ttKey {
  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. wxKey, _ := global.App.Redis.Keys(context.Background(), userKeyWx).Result()
  303. for _, v := range wxKey {
  304. res, err2 := global.App.Redis.HGetAll(context.Background(), v).Result()
  305. if err2 != nil {
  306. continue
  307. }
  308. userId, _ := strconv.Atoi(res["userId"])
  309. registerTimeUnix, _ := strconv.Atoi(res["registerTime"])
  310. registerTime := time.Unix(int64(registerTimeUnix), 0)
  311. global.App.DB.Table("user").Create(&model.User{
  312. Gid: res["gid"],
  313. Pf: res["pf"],
  314. UserId: userId,
  315. CreatedAt: registerTime,
  316. })
  317. }
  318. }
  319. response.Success(c, gin.H{"data": "success"})
  320. }
  321. func ReceiveAdsInfo(c *gin.Context) {
  322. //response.Success(c, gin.H{"data": "success"})
  323. //return
  324. form := request.Check(c, &struct {
  325. Aid string `form:"aid" json:"aid" binding:""`
  326. Pid string `form:"pid" json:"pid" binding:""`
  327. Cid string `form:"cid" json:"cid" binding:""`
  328. }{})
  329. //存储参数
  330. global.App.Log.Info("ReceiveAdsInfo", form)
  331. gid := c.GetString("gid")
  332. pf := c.GetString("pf")
  333. openId := c.GetString("openid")
  334. userId := gid + "|" + pf + "|" + openId
  335. global.App.Log.Info("userId", userId)
  336. id := userId + "|" + form.Aid
  337. aid, _ := strconv.Atoi(form.Aid)
  338. pid, _ := strconv.Atoi(form.Pid)
  339. collection := global.App.MongoDB.Database("chunhao").Collection("adRelated")
  340. var adRelated model.AdRelated
  341. filter := bson.M{"_id": id}
  342. collection.FindOne(context.Background(), filter).Decode(&adRelated)
  343. if adRelated.Id == "" {
  344. //新增
  345. adData := model.AdRelated{
  346. UserId: userId,
  347. Id: id,
  348. Aid: int64(aid),
  349. Pid: int64(pid),
  350. Cid: form.Cid,
  351. Duration: 0,
  352. StartNum: 1,
  353. Revenue: 0,
  354. ReqCount: 0,
  355. ExpCount: 0,
  356. CreateTime: time.Now().Unix(),
  357. }
  358. //更新到MongoDB 中
  359. _, err := collection.InsertOne(context.Background(), adData)
  360. if err != nil {
  361. response.Fail(c, 1003, "写入数据失败"+err.Error())
  362. return
  363. }
  364. }
  365. ////关联到userInfo 上
  366. //filter = bson.M{"_id": userId}
  367. //update := bson.M{
  368. // "$set": struct {
  369. // RelatedAid int64 `bson:"relatedAid" json:"relatedAid"`
  370. // }{
  371. // RelatedAid: int64(aid),
  372. // },
  373. //}
  374. //collection = global.App.MongoDB.Database("chunhao").Collection("userBehavior")
  375. //_, err := collection.UpdateOne(context.Background(), filter, update)
  376. //if err != nil {
  377. // response.Fail(c, 1003, err.Error())
  378. // return
  379. //}
  380. response.Success(c, gin.H{"data": "success"})
  381. }
  382. func SetLocalActiveLog(gid string, pf string, openId string, userId int, types int, now time.Time) error {
  383. // 生成日期目录路径(示例:./data/2024-06-15)
  384. dateDir := now.Format("2006-01-02")
  385. dirPath := filepath.Join("storage", dateDir)
  386. // 创建日期目录(若不存在)
  387. if err := os.MkdirAll(dirPath, 0755); err != nil {
  388. return err
  389. }
  390. // 生成文件名(示例:g123_wechat.txt)
  391. fileName := fmt.Sprintf("%s_%s.txt", gid, pf)
  392. filePath := filepath.Join(dirPath, fileName)
  393. // 追加写入文件
  394. file, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
  395. if err != nil {
  396. return fmt.Errorf("failed to open file: %v", err)
  397. }
  398. defer file.Close()
  399. // 写入数据(示例:1584,oXyZ123456\n)
  400. if _, err := fmt.Fprintf(file, "%d,%d,%s\n", userId, types, now.Format("2006-01-02 15:04:05")); err != nil {
  401. return fmt.Errorf("failed to write file: %v", err)
  402. }
  403. return nil
  404. }