wucan 7 ماه پیش
والد
کامیت
388b4acea8
3فایلهای تغییر یافته به همراه252 افزوده شده و 9 حذف شده
  1. 170 0
      controller/v1/behavior.go
  2. 79 9
      controller/v1/user.go
  3. 3 0
      route/api.go

+ 170 - 0
controller/v1/behavior.go

@@ -7,8 +7,11 @@ import (
 	"designs/global"
 	"designs/service"
 	"encoding/json"
+	"errors"
 	"github.com/gin-gonic/gin"
 	"go.mongodb.org/mongo-driver/v2/bson"
+	"strconv"
+	"time"
 )
 
 type AdData struct {
@@ -210,3 +213,170 @@ func UpdateUserBehavior(c *gin.Context) {
 		"data": result,
 	})
 }
+
+func FindUserBehavior(id string) *UserBehavior {
+	filter := bson.M{"_id": id}
+	var result UserBehavior
+	collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
+	err := collection.FindOne(context.Background(), filter).Decode(&result)
+	if err != nil {
+		return nil
+	}
+
+	return &result
+}
+
+// 新建UserBehavior
+func CreateUserBehavior(gid string, pf string, openId string) error {
+	id := gid + "|" + pf + "|" + openId
+
+	Behavior := FindUserBehavior(id)
+	if Behavior != nil {
+		return errors.New("该用户数据已经存在")
+	}
+
+	behavior := UserBehavior{
+		Id:                 id,
+		Gid:                gid,
+		Pf:                 pf,
+		OpenId:             openId,
+		AdData:             nil,
+		AdFromCount:        0,
+		TotalDuration:      0,
+		TotalAdReqCount:    0,
+		TotalAdEposedCount: 0,
+	}
+	//新增
+	collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
+	_, err := collection.InsertOne(context.Background(), behavior)
+	if err != nil {
+		return err
+	}
+	return nil
+}
+
+// 更新UserBehavior 在线时间
+func UpdateUserBehaviorDuration(gid string, pf string, openId string, now time.Time, types int) error {
+	id := gid + "|" + pf + "|" + openId
+	Behavior := FindUserBehavior(id)
+	if Behavior == nil {
+		return errors.New("该用户数据未保存,无法计算在线时间")
+	}
+
+	lastTime, err := global.App.Redis.Get(context.Background(), id+"|online").Result()
+	if err != nil {
+		return err
+	}
+
+	//当状态为在线时,刷新redis数据,状态为2是离线,不刷新
+	if types == 1 {
+		global.App.Redis.Set(context.Background(), id+"|online", now.Unix(), 300)
+	} else {
+		global.App.Redis.Del(context.Background(), id+"|online")
+	}
+
+	//如果redis中没有查到在线状态,那就视为刚刚登录,不增加时间
+	if lastTime == "" {
+		return nil
+	}
+
+	//计算时间差
+	lastTimeUnix, _ := strconv.ParseInt(lastTime, 10, 64)
+	duration := now.Unix() - lastTimeUnix
+
+	var adData interface{}
+	if Behavior.AdData != nil {
+		//存在adData
+		var newAdData AdData
+		oldAdDatas, _ := json.Marshal(Behavior.AdData)
+		json.Unmarshal(oldAdDatas, &newAdData)
+
+		newAdData.Duration = newAdData.Duration + duration
+		adData = newAdData
+	}
+
+	//更新到MongoDB 中
+	update := bson.M{
+		"$set": struct {
+			AdData        interface{} `bson:"adData" json:"adData"`
+			TotalDuration int         `bson:"duration" json:"duration"`
+		}{
+			AdData:        adData,
+			TotalDuration: Behavior.TotalDuration + int(duration),
+		},
+	}
+	filter := bson.M{"_id": id}
+	collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
+	_, err = collection.UpdateOne(context.Background(), filter, update)
+	if err != nil {
+		return err
+	}
+
+	return nil
+}
+
+// 更新UserBehavior 看广告的数据
+func UpdateUserBehaviorAdInfo(gid string, pf string, openId string, adsState int) error {
+	id := gid + "|" + pf + "|" + openId
+
+	collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
+	filter := bson.M{"_id": id}
+
+	Behavior := FindUserBehavior(id)
+	if Behavior == nil {
+		return errors.New("该用户数据未保存,无法计算在线时间")
+	}
+	var adData interface{}
+	if Behavior.AdData != nil {
+		//存在adData
+		var newAdData AdData
+		oldAdDatas, _ := json.Marshal(Behavior.AdData)
+		json.Unmarshal(oldAdDatas, &newAdData)
+
+		newAdData.AdReqCount++
+		if adsState == 2 {
+			newAdData.AdEposedcount++
+		}
+
+		adData = newAdData
+	}
+
+	var AdReqCount int
+	var AdEposedcount int
+	var AdFormCount int
+	if adsState == 0 {
+		//展示不成功
+		AdReqCount = 1
+		AdFormCount = 1
+	} else if adsState == 1 {
+		//展示成功
+		AdReqCount = 1
+		AdFormCount = 1
+	} else if adsState == 2 {
+		//展示成功并且看完
+		AdReqCount = 1
+		AdFormCount = 1
+		AdEposedcount = 1
+	}
+
+	//更新到MongoDB 中
+	update := bson.M{
+		"$set": struct {
+			AdData             interface{} `bson:"adData" json:"adData"`
+			AdFromCount        int         `bson:"adFromCount" json:"adFromCount"`
+			TotalAdReqCount    int         `bson:"totalAdReqCount" json:"totalAdReqCount"`
+			TotalAdEposedCount int         `bson:"totalAdEposedCount" json:"totalAdEposedCount"`
+		}{
+			AdData:             adData,
+			AdFromCount:        Behavior.AdFromCount + AdFormCount,
+			TotalAdReqCount:    Behavior.TotalAdReqCount + AdReqCount,
+			TotalAdEposedCount: Behavior.TotalAdEposedCount + AdEposedcount,
+		},
+	}
+
+	_, err := collection.UpdateOne(context.Background(), filter, update)
+	if err != nil {
+		return err
+	}
+	return nil
+}

+ 79 - 9
controller/v1/user.go

@@ -12,6 +12,7 @@ import (
 	"fmt"
 	"github.com/gin-gonic/gin"
 	"github.com/pkg/errors"
+	"go.mongodb.org/mongo-driver/v2/bson"
 	"strconv"
 	"strings"
 	"time"
@@ -35,22 +36,22 @@ func ReceiveGameMsg(c *gin.Context) {
 
 	gid := c.GetString("gid")
 	pf := c.GetString("pf")
-	//openId := c.GetString("openid")
+	openId := c.GetString("openid")
 
 	now := time.UnixMilli(form.Timestamp)
 	var err error
 	if form.Action == "login" {
 		//登录
-		err = login(gid, pf, form.UserId, now)
+		err = login(gid, pf, openId, form.UserId, now)
 	} else if form.Action == "online" {
 		//活跃
-		err = online(gid, pf, form.UserId, now)
+		err = online(gid, pf, openId, form.UserId, now)
 	} else if form.Action == "offline" {
 		//断开
-		err = offline(gid, pf, form.UserId, now)
+		err = offline(gid, pf, openId, form.UserId, now)
 	} else if form.Action == "seeAds" {
 		//观看广告
-		err = seeAds(gid, pf, form.UserId, now, form.AdsId, form.AdsType, form.AdsScene, form.AdsState)
+		err = seeAds(gid, pf, openId, form.UserId, now, form.AdsId, form.AdsType, form.AdsScene, form.AdsState)
 	} else {
 		//自定义类型
 		//查询有无对应的行为记录
@@ -129,7 +130,7 @@ func action(gid string, pf string, gameActionId string, userId int, now time.Tim
 	return nil
 }
 
-func login(gid string, pf string, userId int, now time.Time) error {
+func login(gid string, pf string, openId string, userId int, now time.Time) error {
 	var user model.User
 	err := global.App.DB.Table("user").Where("gid", gid).Where("pf", pf).Where("userId", userId).First(&user).Error
 	if user.ID == 0 {
@@ -171,10 +172,15 @@ func login(gid string, pf string, userId int, now time.Time) error {
 		return err
 	}
 
+	err = CreateUserBehavior(gid, pf, openId)
+	if err != nil {
+		global.App.Log.Error("存储用户信息进入mongo失败", err.Error(), userOnline)
+	}
+
 	return nil
 }
 
-func online(gid string, pf string, userId int, now time.Time) error {
+func online(gid string, pf string, openId string, userId int, now time.Time) error {
 
 	userOnline := model.UserOnline{
 		Gid:     gid,
@@ -189,10 +195,16 @@ func online(gid string, pf string, userId int, now time.Time) error {
 		global.App.Log.Error("存储用户活跃信息失败", err.Error(), userOnline)
 		return err
 	}
+
+	err = UpdateUserBehaviorDuration(gid, pf, openId, now, 1)
+	if err != nil {
+		global.App.Log.Error("存储用户在线时长mongo失败", err.Error(), userOnline)
+	}
+
 	return nil
 }
 
-func offline(gid string, pf string, userId int, now time.Time) error {
+func offline(gid string, pf string, openId string, userId int, now time.Time) error {
 
 	userOnline := model.UserOnline{
 		Gid:     gid,
@@ -208,10 +220,14 @@ func offline(gid string, pf string, userId int, now time.Time) error {
 		return err
 	}
 
+	err = UpdateUserBehaviorDuration(gid, pf, openId, now, 2)
+	if err != nil {
+		global.App.Log.Error("存储用户在线时长mongo失败", err.Error(), userOnline)
+	}
 	return nil
 }
 
-func seeAds(gid string, pf string, userId int, now time.Time, AdsId string, AdsType string, AdsScene string, AdsState int) error {
+func seeAds(gid string, pf string, openId string, userId int, now time.Time, AdsId string, AdsType string, AdsScene string, AdsState int) error {
 	if AdsId == "" || AdsType == "" || AdsScene == "" {
 		return errors.New("参数缺失")
 	}
@@ -233,6 +249,11 @@ func seeAds(gid string, pf string, userId int, now time.Time, AdsId string, AdsT
 		return err
 	}
 
+	err = UpdateUserBehaviorAdInfo(gid, pf, openId, AdsState)
+	if err != nil {
+		global.App.Log.Error("存储用户观看广告mongo失败", err.Error(), userOnline)
+	}
+
 	return nil
 }
 
@@ -302,3 +323,52 @@ func InitUser(c *gin.Context) {
 
 	response.Success(c, gin.H{"data": "success"})
 }
+
+func ReceiveAdsInfo(c *gin.Context) {
+	form := request.Check(c, &struct {
+		Aid string `form:"aid" json:"aid" binding:"required"`
+		Pid string `form:"pid" json:"pid" binding:"required"`
+		Cid string `form:"cid" json:"cid" binding:"required"`
+	}{})
+	gid := c.GetString("gid")
+	pf := c.GetString("pf")
+	openId := c.GetString("openid")
+
+	id := gid + "|" + pf + "|" + openId
+
+	collection := global.App.MongoDB.Database("chunhao").Collection("userBehavior")
+	filter := bson.M{"_id": id}
+	result := make(map[string]interface{})
+	err := collection.FindOne(context.Background(), filter).Decode(&result)
+	if err != nil {
+		response.Fail(c, 1003, err.Error())
+		return
+	}
+
+	adData := AdData{
+		Aid:           form.Aid,
+		Pid:           form.Pid,
+		Cid:           form.Cid,
+		Reported:      false,
+		Duration:      0,
+		AdReqCount:    0,
+		AdEposedcount: 0,
+		CreateTime:    int(time.Now().Unix()),
+	}
+
+	//更新到MongoDB 中
+	update := bson.M{
+		"$set": struct {
+			AdData AdData `bson:"adData" json:"adData"`
+		}{
+			AdData: adData,
+		},
+	}
+	_, err = collection.UpdateOne(context.Background(), filter, update)
+	if err != nil {
+		response.Fail(c, 1003, "写入数据失败"+err.Error())
+		return
+	}
+
+	response.Success(c, gin.H{"data": "success"})
+}

+ 3 - 0
route/api.go

@@ -18,6 +18,9 @@ func SetApiGroupRoutes(router *gin.RouterGroup) {
 	GroupV1.Use(middleware.TokenAuthMiddleware()).Use()
 	{
 		GroupV1.POST("/user/receiveGameMsg", v1.ReceiveGameMsg)
+
+		GroupV1.POST("/user/receiveAdsInfo", v1.ReceiveAdsInfo)
+
 		GroupV1.POST("/user/receiveUserBehavior", v1.ReceiveUserBehavior)
 		GroupV1.POST("/user/checkUserBehavior", v1.CheckUserBehavior)
 	}