user.go 14 KB

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