Commit d8f57d9c authored by hujiebin's avatar hujiebin

feat:还有一半的group接口

parent 5742f471
...@@ -139,3 +139,19 @@ var GROUP_INTRODUCTION_LENGTH_LIMIT = 500 ...@@ -139,3 +139,19 @@ var GROUP_INTRODUCTION_LENGTH_LIMIT = 500
const ROOM_PASSWORD_LENGTH = 4 const ROOM_PASSWORD_LENGTH = 4
const SETTING_CUSTOMIZED = 2 const SETTING_CUSTOMIZED = 2
const SETTING_OFFICIAL = 1 const SETTING_OFFICIAL = 1
type AddGroupResultType = uint
const (
ADD_GROUP_DONE AddGroupResultType = 1
ADD_GROUP_DUPLICATE AddGroupResultType = 2
ADD_GROUP_PENDING AddGroupResultType = 3
ADD_GROUP_FAILED AddGroupResultType = 0
)
var GROUP_DEFAULT_JOIN_LIMIT uint = 200
var GROUP_VIP_JOIN_LIMIT uint = 500
var GROUP_NOBLE4_JOIN_LIMIT uint = 1000
var GROUP_ROLE_PERSONAL_VIEW_LIMIT = 5
var GROUP_MANAGER_LIMIT uint = 30
var GROUP_ADMIN_LIMIT uint = 50
package tim_e
// TIM相关常量
const (
SYNC_TO_SENDER = 1
NOSYNC_TO_SENDER = 2
TAG_PROFILE_IM_LEVEL = "Tag_Profile_IM_Level"
TAG_PROFILE_IM_NICK = "Tag_Profile_IM_Nick"
TAG_PROFILE_IM_IMAGE = "Tag_Profile_IM_Image"
TAG_PROFILE_IM_HILO = "Tag_Profile_Custom_Hilo"
)
...@@ -17,6 +17,7 @@ import ( ...@@ -17,6 +17,7 @@ import (
"hilo-group/domain/model/res_m" "hilo-group/domain/model/res_m"
"hilo-group/domain/model/rocket_m" "hilo-group/domain/model/rocket_m"
"hilo-group/domain/service/group_s" "hilo-group/domain/service/group_s"
"hilo-group/myerr"
"sort" "sort"
) )
...@@ -379,3 +380,18 @@ func BuildJoinedGroupInfo(myService *domain.Service, myUserId uint64, groupIds [ ...@@ -379,3 +380,18 @@ func BuildJoinedGroupInfo(myService *domain.Service, myUserId uint64, groupIds [
} }
return result, len(groupInfo), nil return result, len(groupInfo), nil
} }
//检查群组中是否有有人在麦上,返回存在的Set[imGroupId]
func CheckMicHasUserByGroup(groupIds []string) (map[string]struct{}, error) {
groupMap := map[string]struct{}{}
for i := 0; i < len(groupIds); i++ {
flag, err := group_m.CheckGroupMicHasUser(groupIds[i])
if err != nil {
return nil, myerr.WrapErr(err)
}
if flag {
groupMap[groupIds[i]] = struct{}{}
}
}
return groupMap, nil
}
...@@ -1033,3 +1033,163 @@ func GetUserBases(userIds []mysql.ID, myUserId mysql.ID) ([]*CvUserBase, error) ...@@ -1033,3 +1033,163 @@ func GetUserBases(userIds []mysql.ID, myUserId mysql.ID) ([]*CvUserBase, error)
} }
return cvUserBases, nil return cvUserBases, nil
} }
func BatchGetUserExtend(model *domain.Model, userIds []mysql.ID, myUserId mysql.ID) (map[mysql.ID]CvUserExtend, error) {
ub, err := GetUserBases(userIds, myUserId)
if err != nil {
return nil, err
}
wg, err := BatchGetWealthGrade(userIds)
if err != nil {
return nil, err
}
cg, err := BatchGetCharmGrade(userIds)
if err != nil {
return nil, err
}
ag, err := BatchGetActiveGrade(userIds)
if err != nil {
return nil, err
}
result := make(map[mysql.ID]CvUserExtend, 0)
for _, i := range ub {
result[*i.Id] = CvUserExtend{
CvUserBase: *i,
WealthGrade: wg[*i.Id],
CharmGrade: cg[*i.Id],
ActiveGrade: ag[*i.Id],
}
}
return result, nil
}
func GetUserBase(userId mysql.ID, myUserId mysql.ID) (*CvUserBase, error) {
var user user_m.User
if err := mysql.Db.First(&user, userId).Error; err != nil {
return nil, myerr.WrapErr(err)
}
isVip, expireTime, err := user_m.IsVip(userId)
if err != nil {
return nil, myerr.WrapErr(err)
}
cvHeadwear, err := headwear_cv.GetCvHeadwear(userId)
if err != nil {
return nil, err
}
logger := mylogrus.MyLog.WithField("func", "GetUserBase")
medals, err := user_m.GetUserMedalMerge(logger, mysql.Db, userId)
if err != nil {
return nil, err
}
medals, medalInfo, err := getMedalInfo(mysql.Db, medals)
if err != nil {
return nil, err
}
up := user_m.UserProperty{}
rides, err := up.BatchGet(mysql.Db, []uint64{userId})
if err != nil {
return nil, err
}
rp := res_m.ResProperty{}
properties, err := rp.GetAll(mysql.Db)
if err != nil {
return nil, err
}
superManagerMap, err := user_m.GetSuperManagerMap([]uint64{userId})
if err != nil {
return nil, err
}
cvUserBase := CvUserBase{
Id: &user.ID,
Avatar: StrNil(IfLogoutStr(IfLogout(user.LogoutTime), "", user.Avatar)),
DefaultAvatar: &user.DefaultAvatar,
ExternalId: StrToString(&user.ExternalId),
Nick: StrNil(IfLogoutNick(IfLogout(user.LogoutTime), user.Code, user.Nick)),
Description: StrNil(IfLogoutStr(IfLogout(user.LogoutTime), "", user.Description)),
Sex: TypeToUint8((*mysql.Type)(&user.Sex)),
Country: StrNil(user.Country),
CountryIcon: StrNil(user.CountryIcon),
Code: StrToString(&user.Code),
IsPrettyCode: user.IsPrettyCode(),
IsVip: isVip,
IsOfficialStaff: superManagerMap[user.ID],
Medals: IfLogoutMedals(IfLogout(user.LogoutTime), []uint32{}, medals),
MedalInfo: IfLogoutMedalInfo(IfLogout(user.LogoutTime), []medal_cv.CvMedal{}, medalInfo),
Headwear: IfLogoutHeadwear(IfLogout(user.LogoutTime), nil, cvHeadwear),
Ride: IfLogoutRide(IfLogout(user.LogoutTime), property_cv.CvProperty{}, property_cv.CvProperty{
Id: rides[user.ID],
PicUrl: properties[rides[user.ID]].PicUrl,
EffectUrl: properties[rides[user.ID]].EffectUrl,
}),
}
noble, err := noble_m.FindActiveNoble(mysql.Db, userId)
if err != nil {
return nil, err
}
if noble != nil {
cvUserBase.Noble = noble_cv.CvNoble{
Level: noble.Level,
EndTime: noble.EndTime.Unix(),
}
}
//本人
if userId == myUserId {
cvUserBase.VipExpireTime = expireTime
cvUserBase.IsShowAge = TypeToUint8((*mysql.Type)(&user.IsShowAge))
cvUserBase.Birthday = BirthdayToUint64(&user.Birthday)
isAgent := user_m.IsAgent(myUserId)
cvUserBase.IsAgentMgr = &isAgent
} else if user.IsShowAge == mysql.OPEN {
cvUserBase.Birthday = BirthdayToUint64(&user.Birthday)
}
//判断是不是工会
userTradeUnion, err := user_m.GetUserTradeUnion(myUserId)
if err != nil {
return nil, err
}
if userTradeUnion == nil {
isTradeUnionFlag := false
cvUserBase.IsTradeUnion = &isTradeUnionFlag
cvUserBase.IsTradeUnionMatchNotification = nil
} else {
isTradeUnionFlag := true
cvUserBase.IsTradeUnion = &isTradeUnionFlag
isTradeUnionMatchNotificationFlag := userTradeUnion.MatchNotification == mysql.OPEN
cvUserBase.IsTradeUnionMatchNotification = &isTradeUnionMatchNotificationFlag
}
return &cvUserBase, nil
}
func getMedalInfo(db *gorm.DB, medals []uint32) ([]uint32, []medal_cv.CvMedal, error) {
resMedals, err := res_m.MedalGetAllMap(db)
if err != nil {
return nil, nil, err
}
// 只选择合法的勋章
validMedals := make([]uint32, 0)
medalInfo := make([]medal_cv.CvMedal, 0)
for _, i := range medals {
if e, ok := resMedals[i]; ok {
validMedals = append(validMedals, i)
medalInfo = append(medalInfo, medal_cv.CvMedal{
Id: i,
PicUrl: e.PicUrl,
EffectUrl: e.SvgaUrl,
})
}
}
return validMedals, medalInfo, nil
}
...@@ -57,11 +57,27 @@ func SetExists(groupId string) (int64, error) { ...@@ -57,11 +57,27 @@ func SetExists(groupId string) (int64, error) {
return redisCli.RedisClient.Exists(context.Background(), key).Result() return redisCli.RedisClient.Exists(context.Background(), key).Result()
} }
func AddGroupMember(groupId string, extIds []string) (int64, error) { func addGroupMember(groupId string, extIds []string) (int64, error) {
key := getGroupMemberKey(groupId) key := getGroupMemberKey(groupId)
return redisCli.RedisClient.SAdd(context.Background(), key, extIds).Result() return redisCli.RedisClient.SAdd(context.Background(), key, extIds).Result()
} }
func AddGroupMember(model *domain.Model, groupId string, extId string) error {
key := getGroupMemberKey(groupId)
ret, err := redisCli.RedisClient.Exists(context.Background(), key).Result()
if err != nil {
model.Log.Infof("AddGroupMember %s, skip because set does not exist", groupId)
return err
}
if ret == 0 {
// 集合不存在,不要加进去!
return nil
}
ret, err = addGroupMember(groupId, []string{extId})
model.Log.Infof("AddGroupMember %s, %s ret = %d, err: %v", groupId, extId, ret, err)
return err
}
func RemoveGroupMember(groupId string, externalId string) (int64, error) { func RemoveGroupMember(groupId string, externalId string) (int64, error) {
key := getGroupMemberKey(groupId) key := getGroupMemberKey(groupId)
return redisCli.RedisClient.SRem(context.Background(), key, externalId).Result() return redisCli.RedisClient.SRem(context.Background(), key, externalId).Result()
...@@ -139,3 +155,26 @@ func SetGroupInfoCache(model *domain.Model, info *group_m.GroupInfo) error { ...@@ -139,3 +155,26 @@ func SetGroupInfoCache(model *domain.Model, info *group_m.GroupInfo) error {
} }
return nil return nil
} }
// 增加领取群组扶持ip次数
func IncrGroupSupportAwardIp(model *domain.Model, ip mysql.Str) (times int64, err error) {
key := group_k.GetGroupSupportAwardIpKey(ip)
times, err = model.Redis.Incr(model, key).Result()
if err != nil {
model.Log.Errorf("IncrGroupSupportAwardIp fail,ip:%v,err:%v", ip, err)
} else {
model.Redis.Expire(model, key, time.Hour*24*6) // 1周1次,ttl=6天吧
}
return
}
// 获取领取群组扶持ip次数
func GetGroupSupportAwardIpTimes(model *domain.Model, ip mysql.Str) (times int64, err error) {
key := group_k.GetGroupSupportAwardIpKey(ip)
times, err = model.Redis.Get(model, key).Int64()
if err != nil && err != redis.Nil {
model.Log.Errorf("GetGroupSupportAwardIpTimes fail,ip:%v,err:%v", ip, err)
return
}
return times, nil
}
package group_ev
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql"
)
type GroupSupportEvent struct {
GroupSupportAwardAdmin GroupSupportItem
GroupCode string
GroupSupportAwardMgrs []GroupSupportItem
}
type GroupSupportItem struct {
GroupSupportAwardId mysql.ID
UserId mysql.ID
DiamondNum uint32
}
func InitGroupSupportEvent(size int, groupCode string) *GroupSupportEvent {
return &GroupSupportEvent{GroupSupportAwardMgrs: make([]GroupSupportItem, 0, size), GroupCode: groupCode}
}
func (groupSupportEvent *GroupSupportEvent) AddAdmin(groupSupportAwardId mysql.ID, userId mysql.ID, diamondNum uint32) *GroupSupportEvent {
groupSupportEvent.GroupSupportAwardAdmin = GroupSupportItem{
GroupSupportAwardId: groupSupportAwardId,
UserId: userId,
DiamondNum: diamondNum,
}
return groupSupportEvent
}
func (groupSupportEvent *GroupSupportEvent) AddMgr(groupSupportAwardId mysql.ID, userId mysql.ID, diamondNum uint32) *GroupSupportEvent {
groupSupportEvent.GroupSupportAwardMgrs = append(groupSupportEvent.GroupSupportAwardMgrs, GroupSupportItem{
GroupSupportAwardId: groupSupportAwardId,
UserId: userId,
DiamondNum: diamondNum,
})
return groupSupportEvent
}
//注册监听
var groupSupportListen = new(domain.EventBase)
//添加领域事件,在每个领域模型中init中添加,因为这是静态业务,非动态的。
func AddGroupSupportSync(callback func(model *domain.Model, event interface{}) error) {
domain.AddEventSync(groupSupportListen, callback)
}
//加入到异步操作中
func AddGroupSupportAsync(callback func(model *domain.Model, event interface{}) error) {
domain.AddEventAsync(groupSupportListen, callback)
}
//领域事件发布
func PublishGroupSupport(model *domain.Model, event interface{}) error {
return domain.PublishEvent(groupSupportListen, model, event)
}
...@@ -2,9 +2,16 @@ package diamond_m ...@@ -2,9 +2,16 @@ package diamond_m
import ( import (
"git.hilo.cn/hilo-common/domain" "git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/mylogrus"
"git.hilo.cn/hilo-common/resource/mysql" "git.hilo.cn/hilo-common/resource/mysql"
"git.hilo.cn/hilo-common/utils"
"gorm.io/gorm"
"hilo-group/_const/enum/diamond_e" "hilo-group/_const/enum/diamond_e"
"hilo-group/domain/model"
"hilo-group/myerr" "hilo-group/myerr"
"hilo-group/myerr/bizerr"
"strconv"
"time"
) )
type DiamondAccount struct { type DiamondAccount struct {
...@@ -61,3 +68,203 @@ func GetDiamondAccountByUserId(model *domain.Model, userId mysql.ID) (*DiamondAc ...@@ -61,3 +68,203 @@ func GetDiamondAccountByUserId(model *domain.Model, userId mysql.ID) (*DiamondAc
diamondAccount.Model = model diamondAccount.Model = model
return &diamondAccount, nil return &diamondAccount, nil
} }
//账号操作配置
type DiamondOperateSet struct {
mysql.Entity
*domain.Model `gorm:"-"`
DiamondNum mysql.NumAll
FrequencyNum mysql.NumAll
FrequencyDay mysql.NumAll
DiamondMaxNum mysql.NumAll
AddReduce mysql.AddReduce
Type diamond_e.OperateType
Name mysql.Str
Status mysql.UserYesNo
DiamondType diamond_e.OperateType
}
//匹配条件扣费
func (diamondAccount *DiamondAccount) ChangeDiamondAccountDetail(operateType diamond_e.OperateType, originId mysql.ID, diamondNum mysql.Num) (*DiamondAccountDetail, error) {
return diamondAccount.addDiamondAccountDetail(operateType, originId, diamondNum)
}
//钻石操作记录,
func (diamondAccount *DiamondAccount) addDiamondAccountDetail(operateType diamond_e.OperateType, originId mysql.ID, diamondNum mysql.Num) (*DiamondAccountDetail, error) {
var diamondOperateSet DiamondOperateSet
var err error
if err = diamondAccount.Db.Where(&DiamondOperateSet{
Type: operateType,
Status: mysql.USER,
DiamondType: 1, // 1:黄钻 2:粉钻
}).First(&diamondOperateSet).Error; err != nil {
return nil, myerr.WrapErr(err)
}
//判断是增加,账号是否被冻结
if diamondAccount.Status == diamond_e.Frozen && diamondOperateSet.AddReduce == mysql.REDUCE {
return nil, bizerr.DiamondAccountFrozen
}
//无限,检查次数
var count int64
if diamondOperateSet.FrequencyDay == -1 {
if diamondOperateSet.FrequencyNum != -1 {
diamondAccount.Db.Model(&DiamondAccountDetail{}).Where(&DiamondAccountDetail{
UserId: diamondAccount.UserId,
OperateType: operateType,
}).Count(&count)
if count >= int64(diamondOperateSet.FrequencyNum) {
return nil, bizerr.DiamondFrequency
//return nil, myerr.NewSysError("钻石操作次数多大, userId:" + mysql.IdToStr(diamondAccount.UserId) + " diamondOperateSetId" + mysql.IdToStr(diamondOperateSet.ID))
}
}
} else if diamondOperateSet.FrequencyDay == 1 {
beginTime, err := time.ParseInLocation("2006-01-02", time.Now().Format("2006-01-02"), time.Local)
if err != nil {
return nil, myerr.WrapErr(err)
}
//一天的次数
diamondAccount.Db.Model(&DiamondAccountDetail{}).Where(&DiamondAccountDetail{
UserId: diamondAccount.UserId,
OperateType: operateType,
}).Where("created_time >= ? ", beginTime).Count(&count)
if count >= int64(diamondOperateSet.FrequencyNum) {
return nil, bizerr.DiamondFrequency
}
//终极拦截,利用
diamondAccount.SetCheckUpdateCondition(" EXISTS (SELECT * from (SELECT COUNT(1) as n from diamond_account_detail d where d.user_id = " + strconv.FormatUint(diamondAccount.UserId, 10) + " and d.operate_type = " + strconv.FormatUint(uint64(operateType), 10) + " and d.created_time >= from_unixtime(" + strconv.FormatInt(utils.GetZeroTime(time.Now()).Unix(), 10) + ")) t where t.n < " + strconv.Itoa(diamondOperateSet.FrequencyNum) + " )")
}
//-1,代表值无效,由参数给与
var upateDiamondNum mysql.Num
if diamondOperateSet.DiamondNum == -1 {
upateDiamondNum = diamondNum
} else {
upateDiamondNum = mysql.Num(diamondOperateSet.DiamondNum)
}
var afterNum mysql.Num
if diamondOperateSet.AddReduce == mysql.ADD {
afterNum = diamondAccount.DiamondNum + upateDiamondNum
} else if diamondOperateSet.AddReduce == mysql.REDUCE {
if diamondAccount.DiamondNum < upateDiamondNum {
return nil, bizerr.DiamondNoEnough
}
afterNum = diamondAccount.DiamondNum - upateDiamondNum
} else {
return nil, myerr.NewSysError("AddReduce 值错误:" + mysql.TypeToString(mysql.Type(diamondOperateSet.AddReduce)))
}
diamondAccountDetail := &DiamondAccountDetail{
Model: diamondAccount.Model,
UserId: diamondAccount.UserId,
DiamondAccountId: diamondAccount.ID,
OperateId: diamondOperateSet.ID,
OperateType: diamondOperateSet.Type,
OriginId: originId,
AddReduce: diamondOperateSet.AddReduce,
Num: upateDiamondNum,
Remark: diamondOperateSet.Name,
BefNum: diamondAccount.DiamondNum,
AftNum: afterNum,
diamondAccount: diamondAccount,
}
return diamondAccountDetail, err
}
func (diamondAccountDetail *DiamondAccountDetail) PersistentNoInTransactional() error {
//fixme: 这里有点奇怪, diamondAccount持久化动作在diamondAccountDetail持久化之后,RowsAffected 就一定是0
txDiamondAccount := diamondAccountDetail.Db.Model(diamondAccountDetail.diamondAccount)
if diamondAccountDetail.diamondAccount.CheckUpdateCondition() {
txDiamondAccount = txDiamondAccount.Where(diamondAccountDetail.diamondAccount.GetUpdateCondition())
}
if diamondAccountDetail.AddReduce == mysql.ADD {
//增加
txDiamondAccount.UpdateColumn("diamond_num", gorm.Expr("diamond_num + ?", diamondAccountDetail.Num))
} else if diamondAccountDetail.AddReduce == mysql.REDUCE {
//减少,保证不能扣成负数
txDiamondAccount.Where("diamond_num >= ?", diamondAccountDetail.Num).UpdateColumn("diamond_num", gorm.Expr("diamond_num - ?", diamondAccountDetail.Num))
} else {
myerr.NewSysError("addReduce 枚举错误 value:" + mysql.TypeToString(mysql.Type(diamondAccountDetail.AddReduce)))
}
if err := txDiamondAccount.Error; err != nil {
return myerr.WrapErr(err)
}
if txDiamondAccount.RowsAffected == 0 {
diamondAccountDetail.Log.Errorf("gorm condition update.RowsAffected = 0,AddReduce:%v", diamondAccountDetail.AddReduce)
return myerr.NewWaring("gorm condition update.RowsAffected = 0")
}
//持久化diamondAccountDetail
if err := model.Persistent(diamondAccountDetail.Db, diamondAccountDetail); err != nil {
return myerr.WrapErr(err)
}
//改变diamondAccount值
if diamondAccountDetail.diamondAccount == nil {
return myerr.NewSysError("持久化错误, 模型:DiamondAccountDetail 中没有diamondAccount, DiamondAccountDetail.Id =" + strconv.Itoa(int(diamondAccountDetail.ID)))
}
var newDiamondAccount DiamondAccount
if err := diamondAccountDetail.Db.First(&newDiamondAccount, diamondAccountDetail.diamondAccount.ID).Error; err != nil {
return myerr.WrapErr(err)
}
if newDiamondAccount.DiamondNum < 0 {
return myerr.NewSysError("diamond_account表中,diamond_num 不能小于0, diamondAccount.id = " + strconv.Itoa(int(newDiamondAccount.ID)))
}
return nil
}
//群组支持
func (diamondAccount *DiamondAccount) GroupSupportAdmin(groupSupportAwardId mysql.ID, diamondNum uint32) (*DiamondAccountDetail, error) {
return diamondAccount.addDiamondAccountDetail(diamond_e.GroupSupportAdmin, groupSupportAwardId, diamondNum)
}
func (diamondAccountDetail *DiamondAccountDetail) Persistent() error {
//fixme: 这里有点奇怪, diamondAccount持久化动作在diamondAccountDetail持久化之后,RowsAffected 就一定是0
txDiamondAccount := diamondAccountDetail.Db.Model(diamondAccountDetail.diamondAccount)
if diamondAccountDetail.diamondAccount.CheckUpdateCondition() {
txDiamondAccount = txDiamondAccount.Where(diamondAccountDetail.diamondAccount.GetUpdateCondition())
}
if diamondAccountDetail.AddReduce == mysql.ADD {
//增加
txDiamondAccount.UpdateColumn("diamond_num", gorm.Expr("diamond_num + ?", diamondAccountDetail.Num))
} else if diamondAccountDetail.AddReduce == mysql.REDUCE {
//减少,保证不能扣成负数
txDiamondAccount.Where("diamond_num >= ?", diamondAccountDetail.Num).UpdateColumn("diamond_num", gorm.Expr("diamond_num - ?", diamondAccountDetail.Num))
} else {
myerr.NewSysError("addReduce 枚举错误 value:" + mysql.TypeToString(mysql.Type(diamondAccountDetail.AddReduce)))
}
if err := txDiamondAccount.Error; err != nil {
return myerr.WrapErr(err)
}
if txDiamondAccount.RowsAffected == 0 {
mylogrus.MyLog.Errorf("gorm condition update.RowsAffected = 0,AddReduce:%v", diamondAccountDetail.AddReduce)
return myerr.NewWaring("gorm condition update.RowsAffected = 0")
}
//持久化diamondAccountDetail
if err := model.Persistent(diamondAccountDetail.Db, diamondAccountDetail); err != nil {
return myerr.WrapErr(err)
}
//改变diamondAccount值
if diamondAccountDetail.diamondAccount == nil {
return myerr.NewSysError("持久化错误, 模型:DiamondAccountDetail 中没有diamondAccount, DiamondAccountDetail.Id =" + strconv.Itoa(int(diamondAccountDetail.ID)))
}
var newDiamondAccount DiamondAccount
if err := diamondAccountDetail.Db.First(&newDiamondAccount, diamondAccountDetail.diamondAccount.ID).Error; err != nil {
return myerr.WrapErr(err)
}
if newDiamondAccount.DiamondNum < 0 {
return myerr.NewSysError("diamond_account表中,diamond_num 不能小于0, diamondAccount.id = " + strconv.Itoa(int(newDiamondAccount.ID)))
}
return nil
}
//群组支持
func (diamondAccount *DiamondAccount) GroupSupportMgr(groupSupportAwardId mysql.ID, diamondNum uint32) (*DiamondAccountDetail, error) {
return diamondAccount.addDiamondAccountDetail(diamond_e.GroupSupportMgr, groupSupportAwardId, diamondNum)
}
...@@ -4,6 +4,7 @@ import ( ...@@ -4,6 +4,7 @@ import (
"git.hilo.cn/hilo-common/domain" "git.hilo.cn/hilo-common/domain"
"gorm.io/gorm" "gorm.io/gorm"
"hilo-group/_const/enum/game_e" "hilo-group/_const/enum/game_e"
"hilo-group/myerr"
"time" "time"
) )
...@@ -78,3 +79,22 @@ func GetNotEndGamesMap(model *domain.Model) map[string][]game_e.GameType { ...@@ -78,3 +79,22 @@ func GetNotEndGamesMap(model *domain.Model) map[string][]game_e.GameType {
} }
return res return res
} }
func IsGaming(model *domain.Model, userId uint64, txGroupId string) (bool, error) {
ids := make([]uint64, 0)
err := model.DB().Table("game_info").Where("tx_group_id = ? and battle_end_at = 0 and status in (0, 1)", txGroupId).Limit(1).Pluck("id", &ids).Error
if err != nil {
return false, myerr.WrapErr(err)
}
if len(ids) > 0 {
userIds := make([]uint64, 0)
err = model.DB().Table("game_player").Where("game_id = ? and user_id = ? and status in (0,1)", ids[0], userId).Limit(1).Pluck("id", &userIds).Error
if err != nil {
return false, myerr.WrapErr(err)
}
if len(userIds) > 0 {
return true, nil
}
}
return false, nil
}
package group_m
import (
"git.hilo.cn/hilo-common/domain"
"gorm.io/gorm"
"hilo-group/myerr"
"hilo-group/myerr/bizerr"
"time"
)
type GroupInviteJoin struct {
Id uint64 `json:"id"`
UserId uint64 `json:"user_id"`
ImGroupId string `json:"im_group_id"`
CreatedTime time.Time `json:"created_time"`
UpdatedTime time.Time `json:"updated_time"`
InviteUserId uint64 `json:"invite_user_id"`
IsAccept int8 `json:"is_accept"`
}
func GetByImGroupId(model *domain.Model, imGroupId string) (*GroupInfo, error) {
if len(imGroupId) <= 0 {
return nil, myerr.WrapErr(bizerr.GroupNotFound)
}
res := new(GroupInfo)
err := model.DB().Where(&GroupInfo{ImGroupId: imGroupId}).First(&res).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return nil, nil
} else {
return nil, myerr.WrapErr(err)
}
}
return res, nil
}
func AcceptGroupInviteJoin(model *domain.Model, userId uint64, imGroupId string) error {
err := model.DB().Exec("update group_invite_join set is_accept = 1 where user_id=? and im_group_id=?", userId, imGroupId).Error
if err != nil {
return myerr.WrapErr(err)
}
return nil
}
func GetGroupInviteJoin(model *domain.Model, userId uint64, imGroupId string) (*GroupInviteJoin, error) {
res := new(GroupInviteJoin)
err := model.DB().Where(&GroupInviteJoin{UserId: userId, ImGroupId: imGroupId}).Where("is_accept=0").First(&res).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return nil, nil
} else {
return nil, myerr.WrapErr(err)
}
}
return res, nil
}
func InsertGroupInviteJoin(model *domain.Model, userId, inviteUserId uint64, imGroupId string) error {
nowTime := time.Now()
sql := "insert into group_invite_join(user_id,invite_user_id,im_group_id,is_accept,created_time,updated_time) " +
"value(?,?,?,?,?,?) on duplicate key update is_accept=?,created_time=?,updated_time=?"
err := model.DB().Exec(sql, userId, inviteUserId, imGroupId, 0, nowTime, nowTime, 0, nowTime, nowTime).Error
if err != nil {
return myerr.WrapErr(bizerr.GroupNotFound)
}
return nil
}
package mgr_m
import (
"database/sql/driver"
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql"
"gorm.io/gorm"
"hilo-group/myerr"
"strings"
"time"
)
type Strs []string
func (this *Strs) Scan(val interface{}) error {
s := val.([]uint8)
ss := strings.Split(string(s), ",")
*this = ss
return nil
}
func (this Strs) Value() (driver.Value, error) {
str := strings.Join(this, ",")
return str, nil
}
//群组Banner
type GroupBanner struct {
mysql.Entity
*domain.Model `gorm:"-"`
Title mysql.Str
Image mysql.Str
Url mysql.Str
GroupCode mysql.Str //群组code
N mysql.Num
Status mysql.UserYesNo
Area int // 上线区域:0全区;1阿语区;2非阿语区;3指定国家
CountryList Strs // 指定区域的国家列表
StartAt int64 // 上架时间戳
EndAt int64 // 下架时间戳
}
func GetGroupBanner(model *domain.Model, id mysql.ID) (*GroupBanner, error) {
groupBanner := GroupBanner{}
if err := model.Db.Model(&GroupBanner{}).First(&groupBanner, id).Error; err != nil {
return &groupBanner, myerr.WrapErr(err)
}
groupBanner.Model = model
return &groupBanner, nil
}
//加入
func AddGroupBanner(model *domain.Model, title mysql.Str, image mysql.Str, url mysql.Str, groupCode mysql.Str, n mysql.Num) *GroupBanner {
return &GroupBanner{
Model: model,
Title: title,
Image: image,
Url: url,
GroupCode: groupCode,
N: n,
Status: mysql.USER,
}
}
//更新
func (groupBanner *GroupBanner) Update(title mysql.Str, image mysql.Str, url mysql.Str, groupCode mysql.Str, n mysql.Num) *GroupBanner {
groupBanner.Title = title
groupBanner.Image = image
groupBanner.Url = url
groupBanner.GroupCode = groupCode
groupBanner.N = n
return groupBanner
}
//上架
func (groupBanner *GroupBanner) User() *GroupBanner {
groupBanner.Status = mysql.USER
return groupBanner
}
//下架
func (groupBanner *GroupBanner) NoUser() *GroupBanner {
groupBanner.Status = mysql.NOUSER
return groupBanner
}
// 房间Banner
type RoomBanner struct {
mysql.Entity
Title mysql.Str
Image mysql.Str
Url mysql.Str
N mysql.Num
Status mysql.UserYesNo
Area int // 上线区域:0全区;1阿语区;2非阿语区;3指定国家
CountryList Strs // 指定区域的国家列表
}
func (rb *RoomBanner) GetRoomBanners(db *gorm.DB, vcAllow bool) ([]RoomBanner, error) {
rows := make([]RoomBanner, 0)
if err := db.Model(&RoomBanner{}).Where(rb).Order("n DESC").Find(&rows).Error; err != nil {
return nil, err
}
res := make([]RoomBanner, 0, len(rows))
for _, v := range rows {
if !vcAllow && v.ID == 241 {
continue
}
res = append(res, v)
}
return res, nil
}
func (rb *RoomBanner) Create(db *gorm.DB) error {
return db.Save(rb).Error
}
func (rb *RoomBanner) Save(db *gorm.DB) error {
return db.Omit("status").Save(rb).Error
}
func (rb *RoomBanner) SetStatus(db *gorm.DB, status uint8) error {
return db.Model(&RoomBanner{}).Where(rb).Update("status", status).Error
}
type DiscoveryBanner struct {
mysql.Entity
*domain.Model `gorm:"-"`
Title mysql.Str
Image mysql.Str
Url mysql.Str
GroupCode mysql.Str
N mysql.Num
BeginTime time.Time
EndTime time.Time
Area int // 上线区域:0全区;1阿语区;2非阿语区;3指定国家
CountryList Strs // 指定区域的国家列表
}
func GetDiscoveryBannerOrErr(model *domain.Model, id mysql.ID) (*DiscoveryBanner, error) {
discoveryBanner := DiscoveryBanner{}
if err := model.Db.Model(&DiscoveryBanner{}).First(&discoveryBanner, id).Error; err != nil {
return &discoveryBanner, myerr.WrapErr(err)
}
discoveryBanner.Model = model
return &discoveryBanner, nil
}
func InitDiscoveryBanner(model *domain.Model, title mysql.Str, image mysql.Str, url mysql.Str, groupCode mysql.Str, n mysql.Num, beginTime time.Time, endTime time.Time) *DiscoveryBanner {
return &DiscoveryBanner{
Model: model,
Title: title,
Image: image,
Url: url,
GroupCode: groupCode,
N: n,
BeginTime: beginTime,
EndTime: endTime,
}
}
//更新
func (discoveryBanner *DiscoveryBanner) Update(title mysql.Str, image mysql.Str, url mysql.Str, groupCode mysql.Str, n mysql.Num, beginTime time.Time, endTime time.Time) *DiscoveryBanner {
discoveryBanner.Title = title
discoveryBanner.Image = image
discoveryBanner.Url = url
discoveryBanner.GroupCode = groupCode
discoveryBanner.N = n
discoveryBanner.BeginTime = beginTime
discoveryBanner.EndTime = endTime
return discoveryBanner
}
func (discoveryBanner *DiscoveryBanner) EditEndTime(time time.Time) *DiscoveryBanner {
discoveryBanner.EndTime = time
return discoveryBanner
}
func (discoveryBanner *DiscoveryBanner) EditBeginTime(time time.Time) *DiscoveryBanner {
discoveryBanner.BeginTime = time
return discoveryBanner
}
package res_m package res_m
import ( import (
"fmt"
"git.hilo.cn/hilo-common/domain" "git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql" "git.hilo.cn/hilo-common/resource/mysql"
"gorm.io/gorm"
"hilo-group/_const/enum/msg_e"
"hilo-group/myerr" "hilo-group/myerr"
) )
...@@ -28,3 +31,20 @@ func CheckCode(model *domain.Model, code string) (bool, error) { ...@@ -28,3 +31,20 @@ func CheckCode(model *domain.Model, code string) (bool, error) {
return false, nil return false, nil
} }
} }
func GetErrByLanguage(db *gorm.DB, msgId msg_e.MsgIdType, lang string, myErr *myerr.BusinessError, args ...interface{}) *myerr.BusinessError {
var msg string
if len(args) > 0 {
msg = fmt.Sprintf(myErr.GetMsg(), args...)
} else {
msg = myErr.GetMsg()
}
if resMul, _ := GetResMultiTextBy(db, msgId, lang); resMul != nil {
if len(args) > 0 {
msg = fmt.Sprintf(resMul.Content, args...)
} else {
msg = resMul.Content
}
}
return myerr.NewBusinessCodeNoCheck(myErr.GetCode(), msg, myerr.BusinessData{})
}
package tim_m
import (
"context"
"encoding/json"
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/mylogrus"
"git.hilo.cn/hilo-common/resource/redisCli"
"git.hilo.cn/hilo-common/sdk/tencentyun"
"hilo-group/_const/enum/msg_e"
"hilo-group/_const/enum/online_e"
"hilo-group/_const/enum/tim_e"
"hilo-group/_const/redis_key"
"hilo-group/domain/model/groupPower_m"
"hilo-group/domain/model/res_m"
"hilo-group/domain/model/user_m"
"runtime/debug"
"strconv"
"time"
)
func FlushGrades(userExtId string, wealthGrade uint32, charmGrade uint32) error {
level := (charmGrade & 0x000000FF << 8) | wealthGrade&0x000000FF
return tencentyun.SetUserLevel(userExtId, level)
}
func SyncWealthGrade(userExtId string, wealthGrade uint32) error {
level, err := tencentyun.GetUserLevel(userExtId)
if err != nil {
return err
}
mylogrus.MyLog.Infof("SyncWealthGrade, user %s, level before = %x, wealthGrade = %d", userExtId, level, wealthGrade)
level = level&0xFFFFFF00 | wealthGrade&0x000000FF
return tencentyun.SetUserLevel(userExtId, level)
}
func SyncCharmGrade(userExtId string, charmGrade uint32) error {
level, err := tencentyun.GetUserLevel(userExtId)
if err != nil {
return err
}
mylogrus.MyLog.Infof("SyncCharmGrade, user %s, level before = %x, charmGrade = %d", userExtId, level, charmGrade)
level = level&0xFFFF00FF | (charmGrade & 0x000000FF << 8)
return tencentyun.SetUserLevel(userExtId, level)
}
type TimHiloInfo struct {
IsVip bool `json:"isVip"`
IsPretty bool `json:"isPretty"`
Medals []uint32 `json:"medals"`
PowerName string `json:"powerName"` // 用户加入的国家势力的绑定群组的名称
NobleLevel uint16 `json:"nobleLevel"`
}
func GetHiloInfo(extId string) (string, error) {
result, err := tencentyun.GetUserHiloInfo(extId)
if err != nil {
return "", err
}
return result, nil
}
func ResetHiloInfo(extId string) error {
info := TimHiloInfo{}
buf, err := json.Marshal(info)
if err != nil {
return err
}
return tencentyun.SetUserHiloInfo(extId, string(buf))
}
func SyncIsVip(model *domain.Model, userId uint64, externalId string) error {
//detail, err := cv.GetUserVip(model, userId)
//if err != nil {
// return err
//}
isVip, _, err := user_m.IsVip(userId)
if err != nil {
return err
}
//isVip := false
//if detail != nil {
// isVip = true
//}
if err = SaveIsVip(externalId, isVip); err != nil {
model.Log.Info("Sync TIM hilo info failed: ", err)
}
return nil
}
func SaveIsVip(extId string, isVip bool) error {
value, err := tencentyun.GetUserHiloInfo(extId)
if err != nil {
return err
}
mylogrus.MyLog.Info("TIM hilo info: ", value)
info := TimHiloInfo{}
if len(value) > 0 {
if err = json.Unmarshal([]byte(value), &info); err != nil {
return err
}
}
info.IsVip = isVip
buf, err := json.Marshal(info)
if err != nil {
return err
}
if err = tencentyun.SetUserHiloInfo(extId, string(buf)); err != nil {
return err
}
return nil
}
func SyncIsPretty(extId string, isPretty bool) error {
value, err := tencentyun.GetUserHiloInfo(extId)
if err != nil {
return err
}
mylogrus.MyLog.Info("TIM hilo info: ", value)
info := TimHiloInfo{}
if len(value) > 0 {
if err = json.Unmarshal([]byte(value), &info); err != nil {
return err
}
}
info.IsPretty = isPretty
buf, err := json.Marshal(info)
if err != nil {
return err
}
if err = tencentyun.SetUserHiloInfo(extId, string(buf)); err != nil {
return err
}
return nil
}
func SyncMedals(model *domain.Model, userId uint64, externalId string) error {
// 同步勋章
medals, err := user_m.GetUserMedalMerge(model.Log, model.Db, userId)
if err != nil {
return nil
}
if err = SaveMedals(externalId, medals); err != nil {
mylogrus.MyLog.Info("Sync TIM hilo info failed: ", err)
}
return nil
}
// fixme:同步贵族信息,购买、续费贵族时需要
func SyncNobleLevel(extId string, nobleLevel uint16) error {
value, err := tencentyun.GetUserHiloInfo(extId)
if err != nil {
return err
}
mylogrus.MyLog.Info("TIM hilo info: ", value)
info := TimHiloInfo{}
if len(value) > 0 {
if err = json.Unmarshal([]byte(value), &info); err != nil {
return err
}
}
info.NobleLevel = nobleLevel
buf, err := json.Marshal(info)
if err != nil {
return err
}
if err = tencentyun.SetUserHiloInfo(extId, string(buf)); err != nil {
return err
}
return nil
}
func SaveMedals(extId string, medals []uint32) error {
value, err := tencentyun.GetUserHiloInfo(extId)
if err != nil {
return err
}
mylogrus.MyLog.Info("TIM hilo info: ", value)
info := TimHiloInfo{}
if len(value) > 0 {
if err = json.Unmarshal([]byte(value), &info); err != nil {
return err
}
}
info.Medals = medals
buf, err := json.Marshal(info)
if err != nil {
return err
}
if err = tencentyun.SetUserHiloInfo(extId, string(buf)); err != nil {
return err
}
return nil
}
// fixme: 以下时机要同步:用户加入/退出势力;势力被取消;势力改绑定群组;群组改名称,欢迎补充
func SyncPowerName(model *domain.Model, userId uint64, externalId string) error {
_, powerName, err := groupPower_m.GetUserGroupPower(model, userId)
if err != nil {
return err
}
if err = SavePowerName(externalId, powerName); err != nil {
mylogrus.MyLog.Info("Sync TIM hilo info failed: ", err)
}
return nil
}
func SavePowerName(extId string, powerName string) error {
value, err := tencentyun.GetUserHiloInfo(extId)
if err != nil {
return err
}
mylogrus.MyLog.Info("TIM hilo info: ", value)
info := TimHiloInfo{}
if len(value) > 0 {
if err = json.Unmarshal([]byte(value), &info); err != nil {
return err
}
}
info.PowerName = powerName
buf, err := json.Marshal(info)
if err != nil {
return err
}
if err = tencentyun.SetUserHiloInfo(extId, string(buf)); err != nil {
return err
}
return nil
}
func SaveNobleLevel(extId string, nobleLevel uint16) error {
value, err := tencentyun.GetUserHiloInfo(extId)
if err != nil {
return err
}
mylogrus.MyLog.Info("TIM hilo info: ", value)
info := TimHiloInfo{}
if len(value) > 0 {
if err = json.Unmarshal([]byte(value), &info); err != nil {
return err
}
}
info.NobleLevel = nobleLevel
buf, err := json.Marshal(info)
if err != nil {
return err
}
if err = tencentyun.SetUserHiloInfo(extId, string(buf)); err != nil {
return err
}
return nil
}
func FlushHiloInfo(extId string, isVip bool, isPrettyCode bool, medals []uint32, groupPowerName string, nobleLevel uint16) error {
info := TimHiloInfo{IsVip: isVip, IsPretty: isPrettyCode, Medals: medals, PowerName: groupPowerName, NobleLevel: nobleLevel}
buf, err := json.Marshal(info)
if err != nil {
return err
}
if err = tencentyun.SetUserHiloInfo(extId, string(buf)); err != nil {
return err
}
return nil
}
func SendGroupInvitationShare(model *domain.Model, fromAccount string, toAccounts []string, txGroupId, faceUrl string, lang string) error {
type TIMInviteEnterRoomMessage struct {
Identifier string `json:"identifier"`
GroupFaceUrl string `json:"groupFaceUrl"`
GroupId string `json:"groupId"`
}
msg := TIMInviteEnterRoomMessage{
Identifier: "TIMGroupInviteMessage",
GroupFaceUrl: faceUrl,
GroupId: txGroupId,
}
buf, err := json.Marshal(msg)
if err != nil {
return err
}
msgBody := string(buf)
/* mt := res_m.ResMultiText{MsgId: common.MSG_ID_GROUP_INVITE, Language: lang}
if err = mt.Get(model.Db); err != nil {
return err
}*/
mt, err := res_m.GetResMultiTextBy(model.Db, msg_e.MSG_ID_GROUP_INVITE, lang)
if err != nil {
return err
}
return tencentyun.BatchSendCustomMsg(model, tim_e.SYNC_TO_SENDER, fromAccount, toAccounts, msgBody, mt.Content)
}
func GetOnlineStatus(model *domain.Model, extIds []string) (map[string]uint, error) {
left := make([]string, 0)
result := make(map[string]uint, 0)
r, err := getOnlineStatus(extIds)
if err != nil {
model.Log.Warnf("getOnlineStatus redis failed")
left = extIds
} else {
model.Log.Infof("getOnlineStatus redis return size = %d: %v", len(r), r)
if len(r) >= len(extIds) {
for i, e := range extIds {
if r[i] == nil {
left = append(left, e)
} else {
switch r[i].(type) {
case string:
s, err := strconv.Atoi(r[i].(string))
if err == nil {
result[e] = uint(s)
} else {
left = append(left, e)
}
default:
model.Log.Infof("getOnlineStatus return unknown type %v for %s", r[i], e)
left = append(left, e)
}
}
}
} else {
left = extIds
}
}
model.Log.Debug("getOnlineStatus cache: ", result)
if len(left) > 0 {
for _, i := range left {
result[i] = online_e.IM_STATUS_OFF_LINE
}
// 异步去取TIM取数据及更新。查不到的就当离线!
go func(userIds []string) {
defer func() {
if r := recover(); r != nil {
mylogrus.MyLog.Errorf("SetOnlineStatus SYSTEM ACTION PANIC: %v, stack: %v", r, string(debug.Stack()))
}
}()
st, err := tencentyun.BatchQueryState(model, userIds)
if err != nil {
return
}
mylogrus.MyLog.Info("getOnlineStatus db: ", st)
for k, v := range st {
if err := setOnlineStatus(k, v, time.Hour*12); err != nil {
model.Log.Warn("SetOnlineStatus failed for ", k)
} else {
model.Log.Infof("SetOnlineStatus done %s - %d", k, v)
}
}
}(left)
}
return result, nil
}
func getOnlineStatus(extIds []string) ([]interface{}, error) {
keys := make([]string, 0)
for _, e := range extIds {
keys = append(keys, redis_key.GetOnLineStatusKey(e))
}
return redisCli.RedisClient.MGet(context.Background(), keys...).Result()
}
func setOnlineStatus(extId string, status uint, ttl time.Duration) error {
key := redis_key.GetOnLineStatusKey(extId)
return redisCli.RedisClient.Set(context.Background(), key, status, ttl).Err()
}
package user_m
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql"
"hilo-group/myerr"
)
//获取用户的国家,和所属的区域(是否阿语区)
func GetUserCountryArea(model *domain.Model, id mysql.ID) (string, int, error) {
type info struct {
Name string
Area int
}
res := new(info)
if err := model.DB().Raw("select name, area from res_country where name = (select country from user where id = ?)", id).First(&res).Error; err != nil {
return "", 0, myerr.WrapErr(err)
}
return res.Name, res.Area, nil
}
package user_m
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql"
"gorm.io/gorm"
"hilo-group/myerr"
)
//用户设备
type UserImei struct {
mysql.Entity
*domain.Model `gorm:"-"`
UserId mysql.ID
Imei mysql.Str
}
func getUserImeiOrCreate(model *domain.Model, userId mysql.ID) (*UserImei, error) {
var userImei UserImei
if err := model.Db.Where(&UserImei{
UserId: userId,
}).First(&userImei).Error; err != nil {
if err == gorm.ErrRecordNotFound {
userImei.UserId = userId
//userImei.Imei = imei
} else {
return nil, myerr.WrapErr(err)
}
}
/* else {
if userImei.Imei == imei {
userImei.SetLasyLoad()
} else {
userImei.Imei = imei
}
}*/
userImei.Model = model
return &userImei, nil
}
func GetUserImeiStr(model *domain.Model, userId mysql.ID) (string, error) {
var userImei UserImei
if err := model.Db.Where(&UserImei{
UserId: userId,
}).First(&userImei).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return "", nil
} else {
return "", myerr.WrapErr(err)
}
}
return userImei.Imei, nil
}
func (userImei *UserImei) updateImei(imei mysql.Str) {
if userImei.Imei == imei {
userImei.SetLasyLoad()
} else {
userImei.Imei = imei
}
}
//统计imei数量
func countImei(model *domain.Model, imei string) (int64, error) {
var c int64 = 0
if err := model.Db.Model(&UserImei{}).Where(&UserImei{
Imei: imei,
}).Count(&c).Error; err != nil {
return 0, myerr.WrapErr(err)
}
return c, nil
}
func ImeiUserIds(model *domain.Model, imei string) ([]uint64, error) {
rows := []UserImei{}
if err := model.Db.Model(&UserImei{}).Where(&UserImei{
Imei: imei,
}).Find(&rows).Error; err != nil {
return nil, myerr.WrapErr(err)
}
userIds := make([]uint64, 0, len(rows))
for _, i := range rows {
userIds = append(userIds, i.UserId)
}
return userIds, nil
}
func GetSameImeiUsers(model *domain.Model, userId uint64) ([]uint64, error) {
userImei, err := getUserImeiOrCreate(model, userId)
if err != nil {
return nil, err
}
if len(userImei.Imei) <= 0 {
return nil, nil
}
userIds, err := ImeiUserIds(model, userImei.Imei)
if err != nil {
return nil, err
}
return userIds, nil
}
func GetSameImeiMap(model *domain.Model, userId uint64) (map[uint64]uint64, error) {
rows, err := GetSameImeiUsers(model, userId)
if err != nil {
return nil, err
}
result := make(map[uint64]uint64, 0)
for _, i := range rows {
result[i] = userId
}
return result, nil
}
package user_m
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql"
"gorm.io/gorm"
"hilo-group/myerr"
"time"
)
//用户IP
type UserIp struct {
mysql.Entity
*domain.Model `gorm:"-"`
UserId mysql.ID
Ip mysql.Str
}
func GetUserIpOrInit(model *domain.Model, userId mysql.ID) (*UserIp, error) {
var userIp UserIp
if err := model.Db.Where(&UserImei{
UserId: userId,
}).First(&userIp).Error; err != nil {
if err == gorm.ErrRecordNotFound {
userIp.UserId = userId
} else {
return nil, myerr.WrapErr(err)
}
}
userIp.Model = model
return &userIp, nil
}
func GetUserIpMap(db *gorm.DB, userIds []uint64) (map[uint64]string, error) {
rows := make([]UserIp, 0)
if err := db.Model(&UserIp{}).Where("user_id IN ?", userIds).Find(&rows).Error; err != nil {
return nil, myerr.WrapErr(err)
}
//
userIpMap := map[uint64]string{}
for _, i := range rows {
userIpMap[i.UserId] = i.Ip
}
return userIpMap, nil
}
//更新Ip
func (userIp *UserIp) UpdateIp(ip string) *UserIp {
userIp.Ip = ip
return userIp
}
//统计imei数量
func countIp(model *domain.Model, ip string, beginTime time.Time) (int64, error) {
var c int64 = 0
if err := model.Db.Model(&UserIp{}).Where(&UserIp{
Ip: ip,
}).Where("created_time >= ?", beginTime).Count(&c).Error; err != nil {
return 0, myerr.WrapErr(err)
}
return c, nil
}
func IpUserIds(model *domain.Model, ip string) ([]uint64, error) {
rows := []UserIp{}
if err := model.Db.Model(&UserIp{}).Where(&UserIp{
Ip: ip,
}).Find(&rows).Error; err != nil {
return nil, myerr.WrapErr(err)
}
userIds := make([]uint64, 0, len(rows))
for _, i := range rows {
userIds = append(userIds, i.UserId)
}
return userIds, nil
}
func GetSameIpUsers(model *domain.Model, userId uint64) ([]uint64, error) {
userIp, err := GetUserIpOrInit(model, userId)
if err != nil {
return nil, err
}
userIds, err := IpUserIds(model, userIp.Ip)
if err != nil {
return nil, err
}
return userIds, nil
}
func GetSameIpUsersMap(model *domain.Model, userId uint64) (map[uint64]struct{}, error) {
rec, err := GetSameIpUsers(model, userId)
if err != nil {
return nil, err
}
result := make(map[uint64]struct{}, 0)
for _, i := range rec {
result[i] = struct{}{}
}
return result, nil
}
...@@ -106,3 +106,15 @@ func GetUserByExtId(model *domain.Model, externalId string) (*User, error) { ...@@ -106,3 +106,15 @@ func GetUserByExtId(model *domain.Model, externalId string) (*User, error) {
user.Model = model user.Model = model
return &user, nil return &user, nil
} }
// 通过externalId批量获取用户
func BatchGetUserByExtIds(model *domain.Model, extIds []string) ([]User, error) {
users := make([]User, 0)
if err := model.Db.Where("external_id IN ?", extIds).Find(&users).Error; err != nil {
return nil, myerr.WrapErr(err)
}
for _, i := range users {
i.Model = model
}
return users, nil
}
package version_m
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql"
)
type VersionControl struct {
mysql.Entity
Platform mysql.Str
AuditVersion mysql.Str
Status mysql.YesNo
}
// 获取所有版本控制
func GetVersionControlByPlatform(model *domain.Model, platform string) *VersionControl {
res := new(VersionControl)
if err := model.Db.Model(VersionControl{}).Where("platform = ?", platform).First(&res).Error; err != nil {
model.Log.Errorf("GetVersionControlByPlatform fail:%v", err)
}
if res.Status != mysql.YES {
res.AuditVersion = "999.999.999" // 不生效设置为无限大
}
return res
}
...@@ -3,14 +3,87 @@ package event_s ...@@ -3,14 +3,87 @@ package event_s
import ( import (
"git.hilo.cn/hilo-common/domain" "git.hilo.cn/hilo-common/domain"
"hilo-group/_const/enum/msg_e" "hilo-group/_const/enum/msg_e"
"hilo-group/domain/event/group_ev"
"hilo-group/domain/event/group_power_ev" "hilo-group/domain/event/group_power_ev"
"hilo-group/domain/model/diamond_m"
"hilo-group/domain/model/groupPower_m" "hilo-group/domain/model/groupPower_m"
"hilo-group/domain/model/msg_m" "hilo-group/domain/model/msg_m"
"hilo-group/domain/model/user_m" "hilo-group/domain/model/user_m"
"strconv"
) )
func EventInit() { func EventInit() {
GroupPowerEvents() GroupPowerEvents()
GroupSupportEvents()
}
func GroupSupportEvents() {
//群组支持
group_ev.AddGroupSupportSync(func(model *domain.Model, e interface{}) error {
event, ok := e.(*group_ev.GroupSupportEvent)
if !ok {
model.Log.Errorf("AddGroupSupportSync fail data")
return nil
}
model.Log.Infof("diamond AddGroupSupport admin:%v mgrs:%v", event.GroupSupportAwardAdmin, event.GroupSupportAwardMgrs)
diamondAccountAdmin, err := diamond_m.GetDiamondAccountByUserId(model, event.GroupSupportAwardAdmin.UserId)
if err != nil {
return err
}
diamondAccountDetailAdmin, err := diamondAccountAdmin.GroupSupportAdmin(event.GroupSupportAwardAdmin.GroupSupportAwardId, event.GroupSupportAwardAdmin.DiamondNum)
if err != nil {
return err
}
if err := diamondAccountDetailAdmin.Persistent(); err != nil {
return err
}
for i, _ := range event.GroupSupportAwardMgrs {
diamondAccount, err := diamond_m.GetDiamondAccountByUserId(model, event.GroupSupportAwardMgrs[i].UserId)
if err != nil {
return err
}
diamondAccountDetail, err := diamondAccount.GroupSupportMgr(event.GroupSupportAwardMgrs[i].GroupSupportAwardId, event.GroupSupportAwardMgrs[i].DiamondNum)
if err != nil {
return err
}
if err := diamondAccountDetail.Persistent(); err != nil {
return err
}
}
return nil
})
//群组支持奖励
group_ev.AddGroupSupportAsync(func(model *domain.Model, e interface{}) error {
event, ok := e.(*group_ev.GroupSupportEvent)
if !ok {
model.Log.Errorf("AddGroupSupportSync fail data")
return nil
}
model.Log.Infof("msg AddGroupSupportAsync admin:%v, mgr:%v", event.GroupSupportAwardAdmin, event.GroupSupportAwardMgrs)
for i, _ := range event.GroupSupportAwardMgrs {
user, err := user_m.GetUser(model, event.GroupSupportAwardMgrs[i].UserId)
if err != nil {
model.Log.Errorf("msg AddGroupSupportAsync GetUser userId:%v, err:%v", event.GroupSupportAwardMgrs[i].UserId, err)
}
if err := msg_m.NewUserRecord(model, user.ID, msg_e.GroupSupport, user.Nick, user.ID, strconv.FormatUint(uint64(event.GroupSupportAwardMgrs[i].DiamondNum), 10), "", "", "", event.GroupCode).Persistent(); err != nil {
model.Log.Errorf("msg AddGroupSupportAsync NewUserRecord err:%v", err)
break
}
msg_m.SendEmasMsgAssistant(model, user.ExternalId, user.DeviceType)
}
user, err := user_m.GetUser(model, event.GroupSupportAwardAdmin.UserId)
if err != nil {
model.Log.Errorf("msg AddGroupSupportAsync GetUser userId:%v, err:%v", event.GroupSupportAwardAdmin.UserId, err)
}
if err := msg_m.NewUserRecord(model, user.ID, msg_e.GroupSupport, user.Nick, user.ID, strconv.FormatUint(uint64(event.GroupSupportAwardAdmin.DiamondNum), 10), "", "", "", event.GroupCode).Persistent(); err != nil {
model.Log.Errorf("msg AddGroupSupportAsync NewUserRecord err:%v", err)
return nil
}
msg_m.SendEmasMsgAssistant(model, user.ExternalId, user.DeviceType)
return nil
})
} }
func GroupPowerEvents() { func GroupPowerEvents() {
......
...@@ -20,7 +20,7 @@ func NewGroupPowerService(myContext *mycontext.MyContext) *GroupPowerService { ...@@ -20,7 +20,7 @@ func NewGroupPowerService(myContext *mycontext.MyContext) *GroupPowerService {
//用户加入国家势力 //用户加入国家势力
func (s *GroupPowerService) GroupPowerUserJoin(groupPowerId mysql.ID, userId mysql.ID) error { func (s *GroupPowerService) GroupPowerUserJoin(groupPowerId mysql.ID, userId mysql.ID) error {
return s.svc.Transactional(func() error { return s.svc.Transactional(func() error {
model := domain.CreateModelContext(s.svc.MyContext) model := domain.CreateModel(s.svc.CtxAndDb)
groupPower, err := groupPower_m.GetGroupPower(model, groupPowerId) groupPower, err := groupPower_m.GetGroupPower(model, groupPowerId)
if err != nil { if err != nil {
return err return err
...@@ -43,7 +43,7 @@ func (s *GroupPowerService) GroupPowerUserJoin(groupPowerId mysql.ID, userId mys ...@@ -43,7 +43,7 @@ func (s *GroupPowerService) GroupPowerUserJoin(groupPowerId mysql.ID, userId mys
func (s *GroupPowerService) GroupPowerUserLeave(groupPowerId mysql.ID, userId mysql.ID) (int, error) { func (s *GroupPowerService) GroupPowerUserLeave(groupPowerId mysql.ID, userId mysql.ID) (int, error) {
remainSeconds := 0 remainSeconds := 0
err := s.svc.Transactional(func() error { err := s.svc.Transactional(func() error {
model := domain.CreateModelContext(s.svc.MyContext) model := domain.CreateModel(s.svc.CtxAndDb)
groupPower, err := groupPower_m.GetGroupPower(model, groupPowerId) groupPower, err := groupPower_m.GetGroupPower(model, groupPowerId)
if err != nil { if err != nil {
return err return err
......
...@@ -4,9 +4,13 @@ import ( ...@@ -4,9 +4,13 @@ import (
"git.hilo.cn/hilo-common/domain" "git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/mycontext" "git.hilo.cn/hilo-common/mycontext"
"git.hilo.cn/hilo-common/resource/config" "git.hilo.cn/hilo-common/resource/config"
"git.hilo.cn/hilo-common/resource/mysql"
"gorm.io/gorm"
"hilo-group/_const/enum/group_e" "hilo-group/_const/enum/group_e"
"hilo-group/_const/redis_key" "hilo-group/_const/redis_key"
"hilo-group/domain/model/group_m" "hilo-group/domain/model/group_m"
"hilo-group/domain/model/noble_m"
"hilo-group/domain/model/user_m"
"strconv" "strconv"
"time" "time"
) )
...@@ -82,3 +86,33 @@ func GetAllSupportLevel(model *domain.Model, date string) (map[string]string, er ...@@ -82,3 +86,33 @@ func GetAllSupportLevel(model *domain.Model, date string) (map[string]string, er
key := redis_key.GetPrefixSupportLevel(date) key := redis_key.GetPrefixSupportLevel(date)
return model.Redis.HGetAll(model, key).Result() return model.Redis.HGetAll(model, key).Result()
} }
func (s *GroupService) GetJoinGroupLimit(userId mysql.ID) (uint, error) {
model := domain.CreateModelContext(s.svc.MyContext)
// 获取群用户上限
maxJoin := group_e.GROUP_DEFAULT_JOIN_LIMIT
isVip, _, err := user_m.IsVip(userId)
if err != nil {
return 0, err
}
if isVip {
maxJoin = group_e.GROUP_VIP_JOIN_LIMIT
}
isNoble4, err := noble_m.CheckNobleLevel(model.Db, userId, 4)
if err != nil {
return 0, err
}
if isNoble4 {
maxJoin = group_e.GROUP_NOBLE4_JOIN_LIMIT
}
guLimit := group_m.GroupUserLimits{UserId: userId}
if err = guLimit.Get(model); err != nil && err != gorm.ErrRecordNotFound {
return 0, err
}
if err != gorm.ErrRecordNotFound {
maxJoin = guLimit.MaxJoin
}
return maxJoin, nil
}
...@@ -2,7 +2,9 @@ package group_s ...@@ -2,7 +2,9 @@ package group_s
import ( import (
"git.hilo.cn/hilo-common/domain" "git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/mylogrus"
"hilo-group/_const/enum/group_e" "hilo-group/_const/enum/group_e"
"hilo-group/domain/cache/group_c"
"hilo-group/domain/model/group_m" "hilo-group/domain/model/group_m"
) )
...@@ -19,3 +21,74 @@ func (s *GroupService) CreateGroup(userId uint64, g *group_m.GroupInfo) error { ...@@ -19,3 +21,74 @@ func (s *GroupService) CreateGroup(userId uint64, g *group_m.GroupInfo) error {
return nil return nil
}) })
} }
// 退群的一系列操作
func (s *GroupService) LeaveGroup(model *domain.Model, groupId string, userId uint64, externalId string) error {
//获取用户是否在麦上, 让用户离开麦
micUser, err := group_m.GetMicUserByExternalId(model, externalId)
if err != nil {
return err
}
if micUser != nil {
if err = micUser.LeaveByUser(userId, externalId); err != nil {
return err
}
}
// 退群后删除管理角色
if err = group_m.RemoveGroupRole(model, groupId, userId); err != nil {
mylogrus.MyLog.Warnf("Can't remove group %s user %d's role.", groupId, userId)
}
// 退群后删除它(可能)作为经理设置的欢迎语
gwt := group_m.GroupWelcomeText{}
if err = gwt.Remove(model.Db, groupId, userId); err != nil {
mylogrus.MyLog.Warnf("Can't remove group %s user %d's welcome text.", groupId, userId)
}
// 退群后删除小闹钟
groupUser := group_m.GroupUser{Model: model, GroupId: groupId, UserId: userId}
if err = groupUser.Delete(); err != nil {
mylogrus.MyLog.Warnf("Can't remove group %s user %d's option.", groupId, userId)
}
// 清理相关缓存
group_c.ClearGroupMemberCount(groupId)
group_c.RemoveGroupMember(groupId, externalId)
return nil
}
// 退出永久会员的一系列操作
func (s *GroupService) LeaveGroupMember(model *domain.Model, groupId string, userId uint64, externalId string) error {
gm := group_m.GroupMember{
GroupId: groupId,
UserId: userId,
}
if err := gm.Remove(model.Db); err != nil {
return err
}
// 退群后删除管理角色
if err := group_m.RemoveGroupRole(model, groupId, userId); err != nil {
mylogrus.MyLog.Warnf("Can't remove group %s user %d's role.", groupId, userId)
}
// 退群后删除它(可能)作为经理设置的欢迎语
gwt := group_m.GroupWelcomeText{}
if err := gwt.Remove(model.Db, groupId, userId); err != nil {
mylogrus.MyLog.Warnf("Can't remove group %s user %d's welcome text.", groupId, userId)
}
// 退群后删除小闹钟
groupUser := group_m.GroupUser{Model: model, GroupId: groupId, UserId: userId}
if err := groupUser.Delete(); err != nil {
mylogrus.MyLog.Warnf("Can't remove group %s user %d's option.", groupId, userId)
}
// 清理相关缓存
group_c.ClearGroupMemberCount(groupId)
group_c.RemoveGroupMember(groupId, externalId)
return nil
}
package group_s
import (
"git.hilo.cn/hilo-common/domain"
"hilo-group/_const/enum/gift_e"
"hilo-group/domain/event/group_ev"
"hilo-group/domain/model/gift_m"
"hilo-group/domain/model/group_m"
"hilo-group/domain/model/res_m"
"hilo-group/domain/model/user_m"
"hilo-group/myerr/bizerr"
"time"
)
// 群组支持名单过滤
func (s *GroupService) GroupSupportList(groupId string, uids []uint64) ([]uint64, []uint64, error) {
if len(uids) <= 0 {
return uids, nil, nil
}
result := make([]uint64, 0)
out := make([]uint64, 0)
err := s.svc.Transactional(func() error {
model := domain.CreateModel(s.svc.CtxAndDb)
// 1. 去掉非群管理者
roles, _, err := group_m.GetRolesInGroup(model, groupId)
if err != nil {
return err
}
userIds := make([]uint64, 0)
for _, i := range uids {
if _, ok := roles[i]; ok {
userIds = append(userIds, i)
} else {
out = append(out, i)
model.Log.Infof("GroupSupportList: rule out %d, no role", i)
}
}
// TODO: 去掉非群成员
//(4)1个账户只能做1个群组的管理员(5)1个设备下只允许领取1个管理奖励
_, _, period := group_m.GetLastSupportPeriod(time.Now())
gsa := group_m.GroupSupportAwardMgr{Period: period}
rows, err := gsa.Get(model.Db)
if err != nil {
return err
}
awards := make(map[uint64]struct{}, 0)
for _, i := range rows {
awards[i.UserId] = struct{}{}
}
uids = userIds
userIds = make([]uint64, 0)
m := make(map[uint64]uint64)
for _, u := range uids {
m, err := user_m.GetSameImeiMap(model, u)
if err != nil {
return err
}
passed := true
for _, i := range m {
if _, ok := awards[i]; ok {
if i == u {
passed = false
model.Log.Infof("GroupSupportList: rule out %d, already awarded", i)
} else {
passed = false
model.Log.Infof("GroupSupportList: rule out %d, imei awarded", i)
}
}
}
if passed == true {
userIds = append(userIds, u)
} else {
out = append(out, u)
}
}
model.Log.Infof("GroupSupportList: uids %v, map %v", uids, m)
_, supportLevel, err := s.GetSupportLevel(groupId)
if err != nil {
return err
}
if uint32(len(userIds)) > supportLevel {
model.Log.Infof("GroupSupportList: rule out %v, limit exeeded", userIds[supportLevel:])
out = append(out, userIds[supportLevel:]...)
userIds = userIds[0:supportLevel]
}
result = userIds
return nil
})
if err == nil {
return result, out, nil
} else {
return nil, nil, err
}
}
func (s *GroupService) GetSupportLevel(groupId string) (uint64, uint32, error) {
model := domain.CreateModel(s.svc.CtxAndDb)
beginTime, endTime, _ := group_m.GetLastSupportPeriod(time.Now())
g := gift_m.GiftOperate{SceneType: gift_e.GroupSceneType, SceneUid: groupId, Model: model}
count, consume, err := g.GetConsumeByRange(beginTime, endTime)
if err != nil {
return 0, 0, err
}
rec, err := res_m.GetResGroupSupportBy(model, count, consume)
if err != nil {
return 0, 0, err
}
if rec != nil {
return rec.ID, rec.MgrNum, nil
}
return 0, 0, nil
}
//群组支持奖励
func (s *GroupService) GroupSupportAward(groupId string, profitAllocator uint64, userIds []uint64, resId uint64, period string) error {
return s.svc.Transactional(func() error {
model := domain.CreateModel(s.svc.CtxAndDb)
//
groupInfo, err := group_m.GetGroupInfo(model, groupId)
if groupInfo == nil {
return bizerr.GroupNotFound
}
//发放奖励
groupSupportAwardAdmin, groupSupportAwardMgrs, err := group_m.AddGroupSupportAward(model, groupId, profitAllocator, resId, userIds, period)
if err != nil {
return err
}
if err := groupSupportAwardAdmin.Persistent(); err != nil {
return err
}
groupSupportEvent := group_ev.InitGroupSupportEvent(len(groupSupportAwardMgrs), groupInfo.Code)
//数据持久化
groupSupportEvent.AddAdmin(groupSupportAwardAdmin.ID, groupSupportAwardAdmin.UserId, groupSupportAwardAdmin.DiamondNum)
for i, _ := range groupSupportAwardMgrs {
if err := groupSupportAwardMgrs[i].Persistent(); err != nil {
return err
}
groupSupportEvent.AddMgr(groupSupportAwardMgrs[i].ID, groupSupportAwardMgrs[i].UserId, groupSupportAwardMgrs[i].DiamondNum)
}
return group_ev.PublishGroupSupport(model, groupSupportEvent)
})
}
func (s *GroupService) RenewGroupSupporter(groupId string, userIds []uint64) error {
return s.svc.Transactional(func() error {
model := domain.CreateModel(s.svc.CtxAndDb)
gs := group_m.GroupSupporter{GroupId: groupId}
if err := gs.Delete(model.Db); err != nil {
return err
}
if len(userIds) > 0 {
gs = group_m.GroupSupporter{GroupId: groupId}
if err := gs.BatchSave(model.Db, userIds); err != nil {
return err
}
}
return nil
})
}
...@@ -46,3 +46,15 @@ func SendSignalMsg(model *domain.Model, groupId string, msg group_m.GroupSystemM ...@@ -46,3 +46,15 @@ func SendSignalMsg(model *domain.Model, groupId string, msg group_m.GroupSystemM
model.Log.Errorf("Marshall failure, msgId = %d : %s", msg.MsgId, err.Error()) model.Log.Errorf("Marshall failure, msgId = %d : %s", msg.MsgId, err.Error())
} }
} }
func SendCustomMsg(model *domain.Model, groupId string, fromAccount *string, content string) (uint, error) {
groupId, err := group_m.ToTxGroupId(model, groupId)
if err != nil {
return 0, err
}
hiloUserInfo := ""
if fromAccount != nil {
hiloUserInfo = group_m.GetHiloUserInfo(model, *fromAccount)
}
return tencentyun.SendCustomMsg(model.Log, groupId, fromAccount, content, hiloUserInfo)
}
...@@ -83,6 +83,7 @@ require ( ...@@ -83,6 +83,7 @@ require (
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.1 // indirect github.com/modern-go/reflect2 v1.0.1 // indirect
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5 // indirect github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.479 // indirect github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.479 // indirect
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ims v1.0.479 // indirect github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ims v1.0.479 // indirect
github.com/tencentyun/tls-sig-api-v2-golang v1.0.0 // indirect github.com/tencentyun/tls-sig-api-v2-golang v1.0.0 // indirect
......
...@@ -294,6 +294,8 @@ github.com/sirupsen/logrus v1.7.0 h1:ShrD1U9pZB12TX0cVy0DtePoCH97K8EtX+mg7ZARUtM ...@@ -294,6 +294,8 @@ github.com/sirupsen/logrus v1.7.0 h1:ShrD1U9pZB12TX0cVy0DtePoCH97K8EtX+mg7ZARUtM
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w=
github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
......
...@@ -10,8 +10,12 @@ var ( ...@@ -10,8 +10,12 @@ var (
ExternalIdNoExist = myerr.NewBusinessCode(1003, "externalId no exist", myerr.BusinessData{}) ExternalIdNoExist = myerr.NewBusinessCode(1003, "externalId no exist", myerr.BusinessData{})
CodeNoExist = myerr.NewBusinessCode(1005, "code no exist", myerr.BusinessData{}) CodeNoExist = myerr.NewBusinessCode(1005, "code no exist", myerr.BusinessData{})
ParaMissing = myerr.NewBusinessCode(1006, "parameter missing", myerr.BusinessData{}) ParaMissing = myerr.NewBusinessCode(1006, "parameter missing", myerr.BusinessData{})
EmptyContent = myerr.NewBusinessCode(1007, "Content is empty", myerr.BusinessData{})
ContentTooLong = myerr.NewBusinessCode(1008, "Content is too long", myerr.BusinessData{})
InvalidParameter = myerr.NewBusinessCode(1009, "Invalid parameter", myerr.BusinessData{}) InvalidParameter = myerr.NewBusinessCode(1009, "Invalid parameter", myerr.BusinessData{})
NotQualified = myerr.NewBusinessCode(1010, "Not qualified", myerr.BusinessData{})
IncorrectState = myerr.NewBusinessCode(1013, "Incorrect state", myerr.BusinessData{}) IncorrectState = myerr.NewBusinessCode(1013, "Incorrect state", myerr.BusinessData{})
UpgradeRequired = myerr.NewBusinessCode(1015, "Version too old. Upgrade is required", myerr.BusinessData{})
TransactionFailed = myerr.NewBusinessCode(1014, "Transaction failed", myerr.BusinessData{}) TransactionFailed = myerr.NewBusinessCode(1014, "Transaction failed", myerr.BusinessData{})
ImagePolicyViolation = myerr.NewBusinessCode(1017, "image policy violation", myerr.BusinessData{}) ImagePolicyViolation = myerr.NewBusinessCode(1017, "image policy violation", myerr.BusinessData{})
ReqTooFrequent = myerr.NewBusinessCode(1018, "Requests are too frequent", myerr.BusinessData{}) ReqTooFrequent = myerr.NewBusinessCode(1018, "Requests are too frequent", myerr.BusinessData{})
...@@ -42,11 +46,23 @@ var ( ...@@ -42,11 +46,23 @@ var (
// 群组 // 群组
GroupNotFound = myerr.NewBusinessCode(14001, "Group not found", myerr.BusinessData{}) // 找不到该群 GroupNotFound = myerr.NewBusinessCode(14001, "Group not found", myerr.BusinessData{}) // 找不到该群
NotGroupMember = myerr.NewBusinessCode(14002, "Not a group member", myerr.BusinessData{}) // 不是群成员
NoPrivileges = myerr.NewBusinessCode(14004, "Not enough permission", myerr.BusinessData{}) // 操作权限不够 NoPrivileges = myerr.NewBusinessCode(14004, "Not enough permission", myerr.BusinessData{}) // 操作权限不够
InBlacklist = myerr.NewBusinessCode(14005, "Can not join the group due to blacklist", myerr.BusinessData{}) // 在群黑名单中,不能进群
OwnerCannotLeave = myerr.NewBusinessCode(14008, "Owner can not leave the group", myerr.BusinessData{}) // 群主不能退群
WrongPasswordLength = myerr.NewBusinessCode(14010, "Incorrect password length", myerr.BusinessData{}) // 密码长度错误 WrongPasswordLength = myerr.NewBusinessCode(14010, "Incorrect password length", myerr.BusinessData{}) // 密码长度错误
GroupIsBanned = myerr.NewBusinessCode(14011, "group is banned by ", myerr.BusinessData{}) // 群已经被管理员封禁 GroupIsBanned = myerr.NewBusinessCode(14011, "group is banned by ", myerr.BusinessData{}) // 群已经被管理员封禁
GroupLimitReached = myerr.NewBusinessCode(14012, "Join group limit reached", myerr.BusinessData{}) // 所在群已达上限
RoleLimitReached = myerr.NewBusinessCode(14013, "Role limit reached", myerr.BusinessData{}) // 所任角色已达上限
GroupCreateLimitReached = myerr.NewBusinessCode(14014, "Create group limit reached", myerr.BusinessData{}) // 你创建的群组数已达上限 GroupCreateLimitReached = myerr.NewBusinessCode(14014, "Create group limit reached", myerr.BusinessData{}) // 你创建的群组数已达上限
GroupLimitReachedVip = myerr.NewBusinessCode(14015, "Join group limit reached. Please purchase VIP", myerr.BusinessData{}) // 所在群已达上限,请购买VIP
GroupAlreadyAwarded = myerr.NewBusinessCode(14016, "Group support awarded", myerr.BusinessData{}) // 群支持奖励已经发放过了
NotManagerOrAdmin = myerr.NewBusinessCode(14017, "Not manager or group admin", myerr.BusinessData{}) // 不是经理或管理员
UserAlreadyAwarded = myerr.NewBusinessCode(14018, "User already awarded", myerr.BusinessData{}) // 用户的群支持奖励已经发放过了
ImeiAlreadyAwarded = myerr.NewBusinessCode(14019, "Imei support awarded", myerr.BusinessData{}) // 设备的群支持奖励已经发放过了
GroupCustomThemeLimit = myerr.NewBusinessCode(14020, "Group Custom Theme Limit", myerr.BusinessData{}) //群主题定制数量只能是5个 GroupCustomThemeLimit = myerr.NewBusinessCode(14020, "Group Custom Theme Limit", myerr.BusinessData{}) //群主题定制数量只能是5个
GroupSupportIpLimit = myerr.NewBusinessCode(14024, "ID:%v is a duplicate account, please select another user to receive the reward", myerr.BusinessData{}) // 群组扶持ip限制
GroupNoPowerToSvip6 = myerr.NewBusinessCode(14026, "Cannot use this permission for SVIP6", myerr.BusinessData{}) // 踢出,无法对SVIP6使用此权限
// 家族 // 家族
GroupPowerHasJoinOther = myerr.NewBusinessCode(15001, "You already have joined power, please exit first", myerr.BusinessData{}) // 已经加入了其它国家势力 GroupPowerHasJoinOther = myerr.NewBusinessCode(15001, "You already have joined power, please exit first", myerr.BusinessData{}) // 已经加入了其它国家势力
...@@ -61,4 +77,7 @@ var ( ...@@ -61,4 +77,7 @@ var (
// 超级管理人 // 超级管理人
OfficialStaffLimit = myerr.NewBusinessCode(22001, "Operation failed", myerr.BusinessData{}) OfficialStaffLimit = myerr.NewBusinessCode(22001, "Operation failed", myerr.BusinessData{})
GamingCannotKick = myerr.NewBusinessCode(27050, "The game has already started and the user cannot be kicked out", myerr.BusinessData{}) // 游戏已经开始,不能踢出用户
) )
...@@ -7,7 +7,10 @@ import ( ...@@ -7,7 +7,10 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"hilo-group/domain/cache/user_c" "hilo-group/domain/cache/user_c"
"hilo-group/domain/model/res_m" "hilo-group/domain/model/res_m"
"hilo-group/myerr"
"hilo-group/myerr/bizerr" "hilo-group/myerr/bizerr"
"strconv"
"strings"
) )
func GetUserId(c *gin.Context) (mysql.ID, error) { func GetUserId(c *gin.Context) (mysql.ID, error) {
...@@ -107,3 +110,47 @@ func GetUserEx(c *gin.Context, myContext *mycontext.MyContext) (mysql.ID, string ...@@ -107,3 +110,47 @@ func GetUserEx(c *gin.Context, myContext *mycontext.MyContext) (mysql.ID, string
} }
return 0, "", "", "", "", bizerr.ParaMissing return 0, "", "", "", "", bizerr.ParaMissing
} }
func GetAppImei(c *gin.Context) (string, error) {
imei := c.GetHeader(mycontext.IMEI)
if len(imei) <= 0 {
return "", myerr.WrapErr(bizerr.ParaMissing)
}
return imei, nil
}
func GetRequestIP(c *gin.Context) string {
reqIP := c.ClientIP()
if reqIP == "::1" {
reqIP = "127.0.0.1"
}
return reqIP
}
func GetAppVersion(c *gin.Context) (string, int, int, int, error) {
deviceType := c.GetHeader(mycontext.DEVICETYPE)
if len(deviceType) <= 0 {
return "", 0, 0, 0, bizerr.ParaMissing
}
appVerStr := c.GetHeader(mycontext.APP_VERSION)
if len(appVerStr) <= 0 {
return "", 0, 0, 0, bizerr.ParaMissing
}
s := strings.Split(appVerStr, ".")
if len(s) < 3 {
return "", 0, 0, 0, bizerr.InvalidParameter
}
major, err := strconv.Atoi(s[0])
if err != nil || major < 0 {
return "", 0, 0, 0, bizerr.InvalidParameter
}
minor, err := strconv.Atoi(s[1])
if err != nil || minor < 0 {
return "", 0, 0, 0, bizerr.InvalidParameter
}
min, err := strconv.Atoi(s[2])
if err != nil || min < 0 {
return "", 0, 0, 0, bizerr.InvalidParameter
}
return deviceType, major, minor, min, nil
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -28,40 +28,40 @@ func InitRouter() *gin.Engine { ...@@ -28,40 +28,40 @@ func InitRouter() *gin.Engine {
imGroup.GET("/group/:code", wrapper(group_r.GetGroupInfo)) imGroup.GET("/group/:code", wrapper(group_r.GetGroupInfo))
imGroup.GET("/detail/:groupId", wrapper(group_r.GetGroupDetail)) imGroup.GET("/detail/:groupId", wrapper(group_r.GetGroupDetail))
imGroup.PUT("/group/:groupId", wrapper(group_r.ModifyGroupInfo)) imGroup.PUT("/group/:groupId", wrapper(group_r.ModifyGroupInfo))
//imGroup.GET("/search/:code", wrapper(SearchGroup)) imGroup.GET("/search/:code", wrapper(group_r.SearchGroup))
//imGroup.DELETE("/member/:groupId", wrapper(LeaveGroup)) imGroup.DELETE("/member/:groupId", wrapper(group_r.LeaveGroup))
//imGroup.PUT("/permanent/:groupId", wrapper(AddPermanentMember)) imGroup.PUT("/permanent/:groupId", wrapper(group_r.AddPermanentMember))
//imGroup.DELETE("/permanent/:groupId", wrapper(RemovePermanentMember)) imGroup.DELETE("/permanent/:groupId", wrapper(group_r.RemovePermanentMember))
//imGroup.GET("/permanent/:groupId", wrapper(GetPermanentMember)) imGroup.GET("/permanent/:groupId", wrapper(group_r.GetPermanentMember))
//imGroup.GET("/myRecent", wrapper(GetRecentGroup)) imGroup.GET("/myRecent", wrapper(group_r.GetRecentGroup))
//imGroup.GET("/myPermanent", wrapper(GetMyGroup)) imGroup.GET("/myPermanent", wrapper(group_r.GetMyGroup))
// //
//imGroup.GET("/visitors/:groupId", wrapper(GetGroupVisitors)) imGroup.GET("/visitors/:groupId", wrapper(group_r.GetGroupVisitors))
//imGroup.GET("/ownPublicGroup/:userExternalId", wrapper(GetOwnPublicGroup)) imGroup.GET("/ownPublicGroup/:userExternalId", wrapper(group_r.GetOwnPublicGroup))
//// 2.19的新接口 //// 2.19的新接口
//imGroup.GET("/ownGroup", wrapper(GetOwnGroup)) imGroup.GET("/ownGroup", wrapper(group_r.GetOwnGroup))
//imGroup.GET("/theirGroup/:userExternalId", wrapper(GetTheirGroups)) imGroup.GET("/theirGroup/:userExternalId", wrapper(group_r.GetTheirGroups))
//imGroup.PUT("/pluginReady/:groupId", wrapper(PluginReady)) imGroup.PUT("/pluginReady/:groupId", wrapper(group_r.PluginReady))
//imGroup.GET("/roomInfo/:groupId", LogRequestTime, wrapper(GetRoomInfo)) imGroup.GET("/roomInfo/:groupId", wrapper(group_r.GetRoomInfo))
// //
//imGroup.GET("/password/:groupId", wrapper(GetGroupPassword)) imGroup.GET("/password/:groupId", wrapper(group_r.GetGroupPassword))
//imGroup.GET("/role/:groupId", wrapper(GetGroupRole)) imGroup.GET("/role/:groupId", wrapper(group_r.GetGroupRole))
//imGroup.PUT("/role/:groupId", wrapper(SetGroupRole)) imGroup.PUT("/role/:groupId", wrapper(group_r.SetGroupRole))
//imGroup.POST("/role/accept", wrapper(AcceptMemberInvite)) imGroup.POST("/role/accept", wrapper(group_r.AcceptMemberInvite))
//imGroup.GET("/admin/:groupId", wrapper(GetGroupAdmin)) imGroup.GET("/admin/:groupId", wrapper(group_r.GetGroupAdmin))
// //
//imGroup.PUT("/blacklist/:groupId", wrapper(AddGroupBlacklist)) imGroup.PUT("/blacklist/:groupId", wrapper(group_r.AddGroupBlacklist))
//imGroup.DELETE("/blacklist/:groupId", wrapper(RemoveGroupBlacklist)) imGroup.DELETE("/blacklist/:groupId", wrapper(group_r.RemoveGroupBlacklist))
//imGroup.GET("/blacklist/:groupId", wrapper(GetGroupBlacklist)) imGroup.GET("/blacklist/:groupId", wrapper(group_r.GetGroupBlacklist))
//imGroup.PUT("/kick/:groupId", wrapper(KickGroupMembers)) imGroup.PUT("/kick/:groupId", wrapper(group_r.KickGroupMembers))
// //
//imGroup.PUT("/allGroupMsg", wrapper(SendTextMsg)) imGroup.PUT("/allGroupMsg", wrapper(group_r.SendTextMsg))
// //
//imGroup.PUT("/welcomeText/:groupId", wrapper(SetWelcomeText)) imGroup.PUT("/welcomeText/:groupId", wrapper(group_r.SetWelcomeText))
//imGroup.GET("/support/page/:groupId", wrapper(GetSupportPage)) imGroup.GET("/support/page/:groupId", wrapper(group_r.GetSupportPage))
//imGroup.GET("/support/detail", wrapper(GetSupportDetail)) imGroup.GET("/support/detail", wrapper(group_r.GetSupportDetail))
//imGroup.GET("/support/award/:groupId", wrapper(TryAddSupporter)) imGroup.GET("/support/award/:groupId", wrapper(group_r.TryAddSupporter))
//imGroup.POST("/support/award/:groupId", wrapper(TakeSupportAward)) imGroup.POST("/support/award/:groupId", wrapper(group_r.TakeSupportAward))
// //
//// 操作类,普通用户不用 //// 操作类,普通用户不用
//imGroup.PUT("/memberLimit", wrapper(SetGroupMemberLimit)) //imGroup.PUT("/memberLimit", wrapper(SetGroupMemberLimit))
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment