...
 
Commits (317)
......@@ -3,7 +3,7 @@ package country_e
import "git.hilo.cn/hilo-common/resource/mysql"
// 国家角色
type CountryMgrRole mysql.Type
type CountryMgrRole uint8
const (
// 国家管理员
......
package groupPower_e
import "git.hilo.cn/hilo-common/resource/mysql"
//国家势力状态
type GroupPowerStatus = mysql.Type
type GroupPowerStatus = uint8
const (
//上架
......@@ -15,17 +13,28 @@ const (
)
//国家势力用户角色
type GroupPowerUserRole = mysql.Type
type GroupPowerUserRole = uint8
const (
//普通用户
GroupPowerUserRoleUser GroupPowerUserRole = 1
//势力主
GroupPowerUserRoleMgr GroupPowerUserRole = 2
//势力管理员
GroupPowerUserRoleAdmin GroupPowerUserRole = 3
)
//国家势力排行榜类型
type GroupPowerRankType = uint8
const (
GroupPowerRankTypeFamous GroupPowerRankType = 1
GroupPowerRankTypeActive GroupPowerRankType = 2
GroupPowerRankTypeCharm GroupPowerRankType = 3
)
//国家势力日志操作类型
type GroupPowerUserLogType = mysql.Type
type GroupPowerUserLogType = uint8
const (
//加入
......@@ -40,7 +49,7 @@ const (
GroupPowerUserLogDissolve GroupPowerUserLogType = 5
)
type GroupPowerDiamondLogType = mysql.Type
type GroupPowerDiamondLogType = uint8
const (
//群组原因加入
......@@ -56,3 +65,7 @@ const (
PowerSuppportAwarded PowerSupportAwardState = 1 // 已经领取
PowerSuppportWaiting PowerSupportAwardState = 2 // 待领取
)
const (
LongestNameplate = 15
)
package groupPower_e
import "git.hilo.cn/hilo-common/resource/mysql"
type GroupPowerGrade int
const (
GroupPowerGrade0 GroupPowerGrade = 0 // 青铜
GroupPowerGrade1 GroupPowerGrade = 1 // 白银
GroupPowerGrade2 GroupPowerGrade = 2 // 黄金
GroupPowerGrade3 GroupPowerGrade = 3 // 黑金
GroupPowerGradeMax = GroupPowerGrade3
)
var (
GroupPowerGradeExp = map[GroupPowerGrade]mysql.Num{
GroupPowerGrade0: 0,
GroupPowerGrade1: 2500000,
GroupPowerGrade2: 15000000,
GroupPowerGrade3: 60000000,
}
)
type GroupPowerPrivilege int
const (
GroupPowerPrivilegeMemberNum GroupPowerPrivilege = 1 // 成员数
GroupPowerPrivilegeMgrNum GroupPowerPrivilege = 2 // 管理员数
GroupPowerPrivilegeNameplate GroupPowerPrivilege = 3 // 家族铭牌
GroupPowerPrivilegeMedal GroupPowerPrivilege = 4 // 家族徽章装饰
GroupPowerPrivilegeNameplateEdit GroupPowerPrivilege = 5 // 编辑铭牌
GroupPowerPrivilegeNameplateHeadwear GroupPowerPrivilege = 6 // 家族头饰
)
package groupPower_e
type GroupPowerStarType int
const (
GroupPowerStarTypeFamous GroupPowerStarType = 1 // 送礼
GroupPowerStarTypeActive GroupPowerStarType = 2 // 活跃
GroupPowerStarTypeCharm GroupPowerStarType = 3 // 收礼
)
func IsGroupPowerStarType(t GroupPowerStarType) bool {
if t != GroupPowerStarTypeFamous && t != GroupPowerStarTypeActive && t != GroupPowerStarTypeCharm {
return false
}
return true
}
......@@ -156,3 +156,11 @@ 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
type GroupProvider = uint8
const (
// 群组声音供应商
GroupProvider_SW GroupProvider = 0 // 声网
GroupProvider_TRTC GroupProvider = 1 // 腾讯trtc
)
......@@ -131,6 +131,10 @@ const (
NewUserRegisterPush2 = 45 // 邀请朋友来Hilo,最高获得100,000钻石奖励!
NewUserRegisterPush3 = 46 // 举办首个活动,领取10,000钻石和35%奖杯奖励!
ActFruitPutRankAward = 47 // 水果机投入排行榜提醒领奖
GroupPowerUpgrade = 48 // 家族升级
GroupPowerExpireNotice = 49 // 家族等级即将过期(每月20日)
GroupPowerWelcomeJoin = 53 // 欢迎加入家族
GroupPowerApplyJoinMsg = 54 // 申请加入家族通知
)
type MsgSysUserType = mysql.Type
......
package groupPower_k
import (
"fmt"
"hilo-group/_const/enum/groupPower_e"
"hilo-group/_const/redis_key"
)
// 家族之星榜单
// type: 1:送礼 2:活跃 3:收礼
// date:天/周/月的开始时间
const GroupPowerStarPrefix = "groupPowerStar:${type}:${period}:${groupPowerId}:${date}" // zset member:userId score:分数
func GetGroupPowerStarRankKey(_type groupPower_e.GroupPowerStarType, period string, groupPowerId uint64, date string) string {
return redis_key.ReplaceKey(GroupPowerStarPrefix,
fmt.Sprintf("%d", _type), period, fmt.Sprintf("%d", groupPowerId), date)
}
package group_k
import (
"fmt"
"hilo-group/_const/redis_key"
)
// 用户进房的key
const (
UserEnterRoomPrefix = "uer:"
UserEnterRoomUserKey = UserEnterRoomPrefix + "u:${user_id}"
UserEnterRoomGroupKey = UserEnterRoomPrefix + "g:${group_id}"
)
func GetUserEnterRoomUserKey(userId uint64) string {
return redis_key.ReplaceKey(UserEnterRoomUserKey, fmt.Sprintf("%d", userId))
}
func GetUserEnterRoomGroupKey(groupId string) string {
return redis_key.ReplaceKey(UserEnterRoomGroupKey, groupId)
}
......@@ -10,9 +10,33 @@ import (
const (
MicPrefix = "mic:"
MicDayInvite = MicPrefix + "day:invite:${userId}:${date}" // string 自动被邀请上麦,1天一次,TTL:24H
MicGroupPowerOnMic = MicPrefix + "groupPower:${userId}:${date}" // 家族内群上麦分钟数
MicUserOnMic = MicPrefix + "user:onMic:${tz}:${userId}:${date}"
MicGroupOnMic = MicPrefix + "group:onMic:${groupId}" // 在群组麦位上的人 hset field:micIndex member:userId
)
func GetUserMicDayInvite(userId mysql.ID) string {
date := time.Now().Format("2006-01-02")
return redis_key.ReplaceKey(MicDayInvite, fmt.Sprintf("%d", userId), date)
}
// 家族内群上麦分钟数
func GetMicGroupPowerOnMic(userId uint64) string {
date := time.Now().Format("2006-01-02")
return redis_key.ReplaceKey(MicGroupPowerOnMic, fmt.Sprintf("%d", userId), date)
}
// 获取用户上麦时间
// 北京、沙特时间
func GetUserOnMicKey(userId uint64, tz, date string) string {
return redis_key.ReplaceKey(MicUserOnMic, tz, fmt.Sprintf("%d", userId), date)
}
// 获取群组麦位上的人
// 可能会有数据不一致,已原来麦位的key为准
// 这里用户快速获取群上麦位的人用,代替大量mget命令慢查询
func GetGroupOnMicUser(groupId string) string {
return redis_key.ReplaceKey(MicGroupOnMic, groupId)
}
package mic_k
// onMic异步入库
const (
OnMicQueue = "onMic:hilo_group"
)
func GetOnMicQueue() string {
return OnMicQueue
}
......@@ -249,6 +249,9 @@ const groupInUserDuration = "group_in_user_duration_{groupUuid}"
// 15天内进入房间的人数
const roomVisitCount = "room_visit_count"
// 15天内进入房间的人数 member groupId score 麦位有人的数量
const roomVisitCountZSet = "room_visit_count_zset"
// 用户进入过的房间及时间
const userEnterRoom = "enter_room_{userId}"
......@@ -261,6 +264,9 @@ const groupPowerDiamond = "group_diamond_{period}"
// 国家Icon
const countryIcon = "contry_icon"
// 国家Area
const countryArea = "contry:area"
// 群贡献前三
const groupTop3Consume = "group_top3_consume_{period}_{groupId}"
......@@ -754,18 +760,27 @@ func GetPrefixGroupMicNumType(groupUuid string) string {
return strings.Replace(groupMicNumType, "{groupUuid}", groupUuid, -1)
}
// Deprecated: 用户进房时间
// 用 uer:g:${group_id}代替
func GetPrefixGroupInUserDuration(groupUuid string) string {
return strings.Replace(groupInUserDuration, "{groupUuid}", groupUuid, -1)
}
// Deprecated: 用户进房时间
// 可用 uer:u:${user_id}代替
func GetUserEnterRoomKey(userId uint64) string {
return strings.Replace(userEnterRoom, "{userId}", strconv.FormatUint(userId, 10), -1)
}
// Deprecated: 用redis集群中的zset代替
func GetPrefixRoomVisitCount() string {
return roomVisitCount
}
func GetPrefixRoomVisitCountZset() string {
return roomVisitCountZSet
}
func GetPrefixSupportLevel(date string) string {
return strings.Replace(supportLevel, "{date}", date, -1)
}
......@@ -778,6 +793,10 @@ func GetCountryIconKey() string {
return countryIcon
}
func GetCountryAreaKey() string {
return countryArea
}
func GetGroupTop3ConsumeKey(period string, groupId string) string {
return strings.Replace(strings.Replace(groupTop3Consume, "{period}", period, -1), "groupId", groupId, -1)
}
......
package common
type MsgIdType = uint
type OnlineStatusType = uint
type GroupRoleType = uint16
type AddGroupResultType = uint
const (
APP_KICKOFF_TIME = "2020-12-19"
DEFAULT_LANG = "en"
DEFAULT_COUNTRY = "KSA"
DEFAULT_NICK = "Hilo No.%s"
DEFAULT_DESCRIPTION = "Welcome to Hilo"
DEFAULT_GROUP_NAME = "Hilo Group NO.%s"
DefaultAvatarMan = "hilo/manager/ea48b62d54a24a709de3c38702c89995.png"
DefaultAvatarWoman = "hilo/manager/ea48b62d54a24a709de3c38702c89995.png"
// 用户视频最低要求时长
BASIC_VIDEO_TIME = 1
// 公会用户视频最低要求时长
GUILD_USER_VIDEO_TIME = 15
STATUS_IN_USE = 1
STATUS_UNUSED = 2
// 公会用户是否打开通知
GuildUserNotifyOn = 1
GuildUserNotifyOff = 2
// 平台
PlatformIOS = 1
PlatformGOOGLE = 2
PlatformEggPlant = 3 // 通过starchat回调的茄子充值
PlatformCheckout = 4
// 加、减
DIRECTION_ADD = 1
DIRECTION_REDUCE = 2
// 操作类型
//发送礼物
OPERATE_TYPE_SENDGIFT = 1
//匹配条件
OPERATE_TYPE_MATCHCONDITION = 2
//建立融云会话
OPERATE_TYPE_SESSIONPAY = 3
//购买钻石
OPERATE_TYPE_BUYDIAMOND = 4
//接受礼物
OPERATE_TYPE_RECEIVEGIFT = 5
//注册
OPERATE_TYPE_REGISTER = 6
//平台赠送
OPERATE_TYPE_MGRSEND = 8
MATCH_CONFIRM_SUCCESS = 1
MATCH_CONFIRM_FAIL = 2
MATCH_CONFIRM_TEMP = 3
ACCEPT_MATCH_CONFIRM = 1
REFUSE_MATCH_CONFIRM = 2
// 视频通话是否达标
VIDEO_EFFECTIVE_YES = 1
VIDEO_EFFECTIVE_NO = 2
// 最大用户相册数
USER_PHOTO_MAX = 9
// 上下架状态
SWITCH_ON = 1
SWITH_OFF = 0
// 群组角色
GROUP_VISITOR GroupRoleType = 0 // 游客
GROUP_MEMBER GroupRoleType = 1 // 成员
GROUP_ADMIN GroupRoleType = 10 // 管理员
GROUP_MANAGER GroupRoleType = 50 // 经理
GROUP_OWNER GroupRoleType = 100 // owner
ROOM_PASSWORD_LENGTH = 4
CREATE_GROUP_MAX_ATTEMPT = 10
// 在线状态
IM_STATUS_OFF_LINE OnlineStatusType = 0
IM_STATUS_PUSH_ON_LINE OnlineStatusType = 1
IM_STATUS_ON_LINE OnlineStatusType = 2
MSG_ID_GROUP_NAME MsgIdType = 101
MSG_ID_GROUP_INTRODUCTION MsgIdType = 102
MSG_ID_GROUP_NOTIFICATION MsgIdType = 103
MSG_ID_GROUP_WELCOME MsgIdType = 104
MSG_ID_GROUP_INVITE MsgIdType = 105
MSG_ID_GROUP_LEAVE_POWER MsgIdType = 106
MSG_ID_ALL_GROUP_ROCKET MsgIdType = 107
MSG_ID_ROOM_MEADAL MsgIdType = 108
MSG_ID_VIDEO_PUSH_TITITLE MsgIdType = 109
MSG_ID_VIDEO_PUSH_CONTENT MsgIdType = 110
MSG_ID_REPEAT_ACCOUNT MsgIdType = 111
MSG_ID_USER_TRANSFER MsgIdType = 114
MSG_ID_NO_POWER_TO_SVIP6 MsgIdType = 115 // 不能对svip6做某些动作
// ps:116-138 在hilo-finance定义了!
MSG_ID_NOT_FAMILY_MEMBER MsgIdType = 165 // 非家族成员
MSG_ID_DEALER_CAN_NOT_SOLE MsgIdType = 166 // 此用户已有家族代理,不能出售钻石
MSG_ID_BUY_FROM_FAMILY MsgIdType = 167 // 请向本家族代理购买钻石
MSG_ID_NEED_JOIN_FAMILY MsgIdType = 168 // 请加入代理的家族后进行购买
MSG_ID_SET_FAMILY_NAMEPL MsgIdType = 169 // 等级不够不能修改家族铭牌
MSG_ID_CHARGE_NO_AREA MsgIdType = 181 // 充值(代理转账,用户给代理充值),失败,不是本区域用户
MSG_ID_BAN_MIC_NOBLE_5 MsgIdType = 188 //无法禁言VIP5和vip6
MSG_ID_KICK_NOBLE_5 MsgIdType = 189 //无法踢出VIP5和vip6
ADD_GROUP_FAILED AddGroupResultType = 0
ADD_GROUP_DONE AddGroupResultType = 1
ADD_GROUP_DUPLICATE AddGroupResultType = 2
ADD_GROUP_PENDING AddGroupResultType = 3
SETTING_OFFICIAL = 1
SETTING_CUSTOMIZED = 2
)
var USER_QPS_DEFAULT_MAX int64 = 15
var HEART_VALUE_MAX uint32 = 2000
var BUILDBOARD_SMALL_SIZE = 30
var BUILDBOARD_SIZE = 50
var GROUP_CREATE_LIMIT = 1
var GROUP_NAME_LENGTH_LIMIT = 30
var GROUP_INTRODUCTION_LENGTH_LIMIT = 500
var GROUP_NOTIFICATION_LENGTH_LIMIT = 150
var MAX_BEAUTIFUL_CODE_LENGTH = 8
var GROUP_DEFAULT_CODE_LENGTH uint16 = 8
var GROUP_DEFAULT_JOIN_LIMIT uint = 200
var GROUP_VIP_JOIN_LIMIT uint = 500
var GROUP_NOBLE4_JOIN_LIMIT uint = 1000
var GROUP_MANAGER_LIMIT uint = 30
var GROUP_ADMIN_LIMIT uint = 50
var GROUP_ROLE_VIEW_LIMIT = 10
var GROUP_ROLE_PERSONAL_VIEW_LIMIT = 5
var GROUP_RECOMMEND_SIZE = 5
var IM_INVALID_USER = "@TLS#NOT_FOUND"
// 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"
)
// 群组内游戏相关
const (
GROUP_DICE_NUM_DEFAULT = 5
GROUP_DICE_NUM_MAX = 5
)
var PAY_TEST_USERS = []uint64{11, 21, 41, 71, 151, 251, 291, 881, 1041, 4411, 951, 24091}
var ROCKET_STAGE_NUM uint16 = 3
var ROCKET_STAGE_CHANGE_THRESHOLD = 10
var ROCKET_SHOW_DURATION = 10
// RocketAwardType
const (
ROCKET_AWARD_GUEST_DIAMOND = 0 // 观众分到小额钻石
ROCKET_AWARD_PROPERTY = 1 // TOP6抽到的座驾
ROCKET_AWARD_HEADDRESS = 2 // TOP6抽到的头饰
ROCKET_AWARD_DIAMOND = 3 // TOP6抽到的钻石
)
const DefaultMinimalVersionAndroid = 100
const DefaultMinimalVersionIOS = 100
const DefaultMsgParallelSize = 20
const OldGroupNamePrefix = "@TGS#"
const NewGroupNamePrefix = "HTGS#"
const OverseaGroupNamePrefix = NewGroupNamePrefix + "a"
const (
SendSmsCodeIpMaxHourTimes = 20
SendSmsCodeImeiMaxHourTimes = 10
SendSmsCodePhoneMaxHourTimes = 5
SendSmsCodeUserMaxHourTimes = 3
SendSmsCodeLen = 6 // 验证码长度
SendSmsCodeMaxCheckTimes = 3 // 验证码最大校验次数
SendSmsCodeNoUserIdMaxHourTimes = 1000 // 没有传userId调用发短信,5分钟最大次数
CallbackCheckoutPaySucceed = "payment_captured" // checkout回调支付成功
// ranking
RankingDay = "day"
RankingWeek = "week"
RankingMonth = "month"
RankingAll = "all"
// ranking module
RankingModulePinkDiamond = "pinkDiamond"
// giftwall 礼物墙
GiftWallInitNum = 15000 // 礼物墙初始化数量
GiftWallInitOnceSetNum = 500 // 礼物墙初始化,一次插入的数量
GiftWallStartReduceNum = 20000 // 礼物墙触发清理逻辑数量
GiftWallReduceNum = 3000 // 礼物墙触发清理逻辑,清理的数量
)
package common
import (
"git.hilo.cn/hilo-common/resource/config"
"strings"
)
// 去除slice中的重复元素
func UniqueSliceUInt64(sliceIn []uint64) []uint64 {
sliceOut := make([]uint64, 0, len(sliceIn))
m := make(map[uint64]struct{}, len(sliceIn))
for _, i := range sliceIn {
if _, ok := m[i]; !ok {
m[i] = struct{}{}
sliceOut = append(sliceOut, i)
}
}
return sliceOut
}
// 补全url,区分处理oss和aws两种情况
func MakeFullUrl(url string) string {
if strings.HasPrefix(url, config.GetConfigOss().OSS_CDN) || strings.HasPrefix(url, config.GetConfigAws().AWS_CDN) {
return url
} else if strings.HasPrefix(url, "nextvideo/") {
return config.GetConfigOss().OSS_CDN + url
} else if strings.HasPrefix(url, config.GetConfigAws().AWS_DIR) {
return config.GetConfigAws().AWS_CDN + url
} else {
return url
}
}
func PageNext(total int64, pageIndex, pageSize int) (int, bool) {
var nextIdx int
var hasNext bool
if total >= int64(pageIndex+pageSize) {
hasNext = true
nextIdx = pageIndex + pageSize
}
return nextIdx, hasNext
}
package utime
import (
"github.com/jinzhu/now"
"time"
)
const (
Day = 86400
Layout = "2006-01-02 15:04:05"
LayoutDay = "2006-01-02"
LayoutDay2 = "20060102"
LayoutMonth = "2006-01"
LayoutMinute = "2006-01-02 15:04"
)
// 获取时间所在周的第一天(周一) 00:00:00,和最后一天(周日)23:59:59
func WeekStartEnd(date time.Time) (start, end time.Time) {
w := 0
week := date.Weekday()
if week == time.Sunday {
w = 7
} else {
w = int(week)
}
startTmp := date.AddDate(0, 0, -w+1)
endTmp := date.AddDate(0, 0, 7-w)
start = time.Date(startTmp.Year(), startTmp.Month(), startTmp.Day(), 0, 0, 0, 0, startTmp.Location())
end = time.Date(endTmp.Year(), endTmp.Month(), endTmp.Day(), 23, 59, 59, 999, endTmp.Location())
return
}
// 当天开始结束
func DayStartEnd(date time.Time) (start, end time.Time) {
start = time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, date.Location())
end = time.Date(date.Year(), date.Month(), date.Day(), 23, 59, 59, 999, date.Location())
return
}
// 获取时间所在月的第一天(1号) 00:00:00,和最后一天23:59:59
func MonthStartEnd(date time.Time) (start, end time.Time) {
start = time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, date.Location())
lastDay := now.New(start).EndOfMonth().Day()
end = time.Date(date.Year(), date.Month(), lastDay, 23, 59, 59, 999999999, date.Location())
return
}
// 增加年/月
// 因为golang原生的Time.AddDate增加月份的时候有bug
func AddDate(t time.Time, years int, months int) time.Time {
year, month, day := t.Date()
hour, min, sec := t.Clock()
// firstDayOfMonthAfterAddDate: years 年,months 月后的 那个月份的1号
firstDayOfMonthAfterAddDate := time.Date(year+years, month+time.Month(months), 1,
hour, min, sec, t.Nanosecond(), t.Location())
// firstDayOfMonthAfterAddDate 月份的最后一天
lastDay := now.New(firstDayOfMonthAfterAddDate).EndOfMonth().Day()
// 如果 t 的天 > lastDay,则设置为lastDay
// 如:t 为 2020-03-31 12:00:00 +0800,增加1个月,为4月31号
// 但是4月没有31号,则设置为4月最后一天lastDay(30号)
if day > lastDay {
day = lastDay
}
return time.Date(year+years, month+time.Month(months), day,
hour, min, sec, t.Nanosecond(), t.Location())
}
......@@ -3,12 +3,26 @@ package cron
import (
"git.hilo.cn/hilo-common/resource/config"
"hilo-group/cron/gift_cron"
"hilo-group/cron/group_cron"
"hilo-group/cron/mic_cron"
"hilo-group/cron/user_cron"
)
func Init() {
user_cron.LoadSvipVipNoble() // 加载用户特权
if !config.IsMaster() {
return
}
gift_cron.SendGiftEventInit() // 礼物消息
gift_cron.GiftRemark() // 礼物消息补偿
//gift_cron.SendGiftEventInit() // 礼物消息
//gift_cron.GiftRemark() // 礼物消息补偿
gift_cron.SendGiftEvent() // 礼物事件
mic_cron.OnMicCheck() // 检查上麦
mic_cron.OnMicQueue() // 检查上麦-队列操作
group_cron.GroupPowerExpClear() // 清理家族经验/等级
group_cron.GroupPowerMonthRankAct()
//group_cron.GroupInEventInit() // 进房事件
//group_cron.CreateGroup() //
group_cron.CalcGroupSupport() // 群组扶持计算
//group_cron.CalcGroupSupport_OldData()
group_cron.GroupCountryListSort()
}
......@@ -30,6 +30,7 @@ func GiftRemark() {
Payload: unmark.Payload,
MarkHiloGroup: unmark.MarkHiloGroup,
Mark: unmark.Mark, // 不能影响别的服务的mark状态
MarkHiloUser: unmark.MarkHiloUser,
}); err != nil {
model.Log.Errorf("FetchUnMarkEvent add unmark fail:%v", err)
continue
......
package gift_cron
import (
"context"
"git.hilo.cn/hilo-common/_const/rediskey"
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql"
"git.hilo.cn/hilo-common/resource/redisCli"
"hilo-group/_const/enum/gift_e"
"hilo-group/_const/enum/groupPower_e"
"hilo-group/domain/cache/gift_c"
"hilo-group/domain/cache/groupPower_c"
"hilo-group/domain/event/gift_ev"
"hilo-group/domain/model/groupPower_m"
"hilo-group/domain/model/group_m"
"time"
)
// 送礼事件
func SendGiftEvent() {
//if !config.IsMaster() {
// return
//}
go func() {
for true {
model := domain.CreateModelNil()
if sendGiftEvent := gift_c.BLPopQueueSendGift(model); sendGiftEvent != nil {
groupPowerGrade(model, sendGiftEvent) // 家族经验
groupPowerStar(model, sendGiftEvent) // 家族之星
groupSupportAddConsume(model, sendGiftEvent) // 群组扶持
}
}
}()
}
// 群组势力经验
func groupPowerGrade(model *domain.Model, sendGiftEvent *gift_ev.SendGiftEvent) {
model.Log.Infof("AddSendGiftEventAsync %+v", sendGiftEvent)
if sendGiftEvent.ResGift.GiftType != mysql.DiamondYellow {
return
}
exist, groupPowerId, err := groupPower_m.CheckGroupPowerUser(model, sendGiftEvent.SendUserId)
if err != nil {
model.Log.Infof("CheckGroupPowerUser fail %+v", err)
return
}
if exist {
exp := sendGiftEvent.GiftN * mysql.Num(len(sendGiftEvent.ReceiveUserIds)) * sendGiftEvent.ResGift.DiamondNum
//return model.Transaction(func(model *domain.Model) error {
// return groupPower_m.IncrGroupPowerExp(model, groupPowerId, exp, sendGiftEvent.SendUserId, "送礼")
//})
//return groupPower_c.QueueGroupPowerGradeExp(model, groupPowerId, exp, sendGiftEvent.SendUserId, "送礼")
if err := model.Transaction(func(model *domain.Model) error {
return groupPower_m.IncrGroupPowerExp(model, groupPowerId, exp, sendGiftEvent.SendUserId, "送礼")
}); err != nil {
model.Log.Errorf("IncrGroupPowerExp fail,data:%v-err:%v", *sendGiftEvent, err)
} else {
model.Log.Infof("IncrGroupPowerExp success,data:%v", *sendGiftEvent)
}
}
}
// 家族之星
func groupPowerStar(model *domain.Model, sendGiftEvent *gift_ev.SendGiftEvent) {
if sendGiftEvent.ResGift.GiftType != mysql.DiamondYellow {
return
}
var userIds = []mysql.ID{sendGiftEvent.SendUserId}
userIds = append(userIds, sendGiftEvent.ReceiveUserIds...)
groupPowers, err := groupPower_m.BatchGetGroupPowerUser(model, userIds)
if err != nil {
model.Log.Errorf("AddSendGiftEventAsync fail:%v", err)
return
}
// 送礼加分
if data, ok := groupPowers[sendGiftEvent.SendUserId]; ok {
diamonds := sendGiftEvent.GiftN * sendGiftEvent.ResGift.DiamondNum * mysql.Num(len(sendGiftEvent.ReceiveUserIds))
if err := groupPower_c.IncrGroupPowerDayStarScore(model, data.GroupPowerId, data.UserId,
groupPower_e.GroupPowerStarTypeFamous, diamonds); err != nil {
model.Log.Errorf("IncrGroupPowerDayStarScore famous fail:%v", err)
}
}
// 收礼加分
for _, userId := range sendGiftEvent.ReceiveUserIds {
if data, ok := groupPowers[userId]; ok {
diamonds := sendGiftEvent.GiftN * sendGiftEvent.ResGift.DiamondNum
if err := groupPower_c.IncrGroupPowerDayStarScore(model, data.GroupPowerId, data.UserId,
groupPower_e.GroupPowerStarTypeCharm, diamonds); err != nil {
model.Log.Errorf("IncrGroupPowerDayStarScore charm fail:%v", err)
}
}
}
return
}
// 群组扶持增加流水数据
func groupSupportAddConsume(model *domain.Model, sendGiftEvent *gift_ev.SendGiftEvent) {
if time.Now().Unix() <= 1693275900 {
return
}
model.Log.Infof("groupSupportAddConsume UserId:%d, sendGiftEvent:%+v", sendGiftEvent.SendUserId, sendGiftEvent)
if sendGiftEvent.SceneType != gift_e.GroupSceneType || sendGiftEvent.SceneUid == "" {
model.Log.Infof("groupSupportAddConsume UserId:%d, sendGiftEvent:%+v", sendGiftEvent.SendUserId, sendGiftEvent)
return
}
_, _, period := group_m.GetSupportLevelTime(time.Now())
// 钻石数
diamond := sendGiftEvent.GiftN * sendGiftEvent.ResGift.DiamondNum * mysql.Num(len(sendGiftEvent.ReceiveUserIds))
keyDiamond := rediskey.GetGroupSupportConsumeSummary(period)
_, err := model.RedisCluster.ZIncrBy(context.Background(), keyDiamond, float64(diamond), sendGiftEvent.SceneUid).Result()
if err != nil {
model.Log.Errorf("groupSupportAddConsume key:%s, val:%d, member:%s, err:%v",
keyDiamond, diamond, sendGiftEvent.SceneUid, err)
}
err = redisCli.SetExpire(model.RedisCluster, keyDiamond, time.Hour*24*14) // 保留两周
if err != nil {
model.Log.Errorf("groupSupportAddConsume key:%s, val:%d, member:%s, err:%v",
keyDiamond, diamond, sendGiftEvent.SceneUid, err)
}
// 支持者数量
keySupportNum := rediskey.GetGroupSupportCountSupporter(period, sendGiftEvent.SceneUid)
err = model.RedisCluster.SAdd(context.Background(), keySupportNum, sendGiftEvent.SendUserId).Err()
if err != nil {
model.Log.Errorf("groupSupportAddConsume key:%s, UserId:%d, err:%v", keySupportNum, sendGiftEvent.SendUserId, err)
}
err = redisCli.SetExpire(model.RedisCluster, keySupportNum, time.Hour*24*14) // 保留两周
if err != nil {
model.Log.Errorf("groupSupportAddConsume key:%s, UserId:%d, err:%v", keySupportNum, sendGiftEvent.SendUserId, err)
}
return
}
package group_cron
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/config"
"github.com/robfig/cron"
"hilo-group/_const/enum/group_e"
"hilo-group/domain/service/group_s"
)
func CreateGroup() {
if !config.IsMaster() {
return
}
c := cron.New()
spec := "0 15 15 16 8 ?"
_ = c.AddFunc(spec, func() {
var model = domain.CreateModelNil()
userId := uint64(7687)
num := 20
if config.AppIsRelease() {
userId = 8350311
num = 1000
}
err := group_s.NewGroupService(model.MyContext).CreateGroupMulByUid(userId, num, group_e.TwoMicNumType)
if err != nil {
model.Log.Errorf("CreateGroupMulByUid fail:%v", err)
}
})
c.Start()
}
package group_cron
import (
"git.hilo.cn/hilo-common/mycontext"
"git.hilo.cn/hilo-common/mylogrus"
"git.hilo.cn/hilo-common/resource/config"
"hilo-group/domain/service/event_s"
"time"
)
// 进房事件
func GroupInEventInit() {
if !config.IsMaster() {
return
}
mylogrus.MyLog.Infof("GroupInEventInit")
go func() {
ticker := time.NewTicker(time.Millisecond * 500)
defer ticker.Stop()
for {
select {
case <-ticker.C:
//start := time.Now()
myCtx := mycontext.CreateMyContext(nil)
// 消费进房事件
if err := event_s.NewGroupInEventService(myCtx).Consume(); err != nil {
myCtx.Log.Errorf("groupInEvent consume fail:%v", err)
} else {
//myCtx.Log.Infof("groupInEvent consume success,cost:%v", time.Now().Sub(start))
}
}
}
}()
}
package group_cron
import (
"git.hilo.cn/hilo-common/domain"
"github.com/robfig/cron"
"hilo-group/domain/service/group_s"
)
// 清理家族经验和等级
func GroupCountryListSort() {
// 常用国家-每15分钟计算国家房间列表排序 /v1/imGroup/country [get] 接口
spec := "0 */15 * * * ?"
c := cron.New()
_ = c.AddFunc(spec, func() {
var model = domain.CreateModelNil()
model.Log.Infof("GroupCountryListSort Common start")
group_s.SortGroupCommonCountryList(model)
model.Log.Infof("GroupCountryListSort Common end")
})
// 非常用国家-每60分钟计算国家房间列表排序 /v1/imGroup/country [get] 接口
spec2 := "0 59 * * * ?"
_ = c.AddFunc(spec2, func() {
var model = domain.CreateModelNil()
model.Log.Infof("GroupCountryListSort not Common start")
group_s.SortGroupNotCommonCountryList(model)
model.Log.Infof("GroupCountryListSort not Common end")
})
c.Start()
}
package group_cron
import (
"git.hilo.cn/hilo-common/domain"
"github.com/robfig/cron"
"hilo-group/domain/event/group_power_ev"
"hilo-group/domain/model/groupPower_m"
)
// 清理家族经验和等级
func GroupPowerExpClear() {
c := cron.New()
// 每月1号0:00经验值清零
spec := "0 0 0 1 * ?"
_ = c.AddFunc(spec, func() {
var model = domain.CreateModelNil()
if err := groupPower_m.ClearGroupPowerExp(model); err != nil {
model.Log.Errorf("ClearGroupPowerExp fail:%v", err)
}
})
// 每分钟清理过期家族等级
spec = "0 * * * * ?"
_ = c.AddFunc(spec, func() {
var model = domain.CreateModelNil()
if err := groupPower_m.ClearGroupPowerGrade(model); err != nil {
model.Log.Errorf("ClearGroupPowerGrade fail:%v", err)
}
})
// 每月20号发家族即将过期通知
spec = "0 0 0 20 * ?"
_ = c.AddFunc(spec, func() {
var model = domain.CreateModelNil()
_ = group_power_ev.PublishGroupPowerExpireNotice(model, &group_power_ev.GroupPowerExpireNoticeEvent{})
})
c.Start()
}
package group_cron
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/config"
"github.com/robfig/cron"
"hilo-group/domain/service/group_power_s"
)
// 家族贡献月度排行榜发奖
func GroupPowerMonthRankAct() {
if !config.IsMaster() {
return
}
c := cron.New()
// 每月1号0:01结算发奖
spec := "0 1 0 1 * ?"
_ = c.AddFunc(spec, func() {
var model = domain.CreateModelNil()
if err := group_power_s.CalcGroupPowerMonthRankAct(model); err != nil {
model.Log.Errorf("GroupPowerMonthRankAct fail:%v", err)
}
})
c.Start()
}
//func BufaGroupPowerMonthRankAct() {
// c := cron.New()
// spec := "0 50 15 1 * ?"
// _ = c.AddFunc(spec, func() {
// var model = domain.CreateModelNil()
// if err := group_power_s.BufaCalcGroupPowerMonthRankAct(model); err != nil {
// model.Log.Errorf("BufaGroupPowerMonthRankAct fail:%v", err)
// }
// })
//
// c.Start()
//}
package group_cron
import (
"context"
"encoding/json"
"git.hilo.cn/hilo-common/_const/rediskey"
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/config"
"git.hilo.cn/hilo-common/resource/redisCli"
"git.hilo.cn/hilo-common/sdk/tencentyun"
"git.hilo.cn/hilo-common/utils"
"github.com/robfig/cron"
"hilo-group/_const/enum/gift_e"
"hilo-group/_const/enum/group_e"
"hilo-group/domain/model/gift_m"
"hilo-group/domain/model/group_m"
"hilo-group/domain/service/group_s"
"time"
)
// 群组扶持计算
func CalcGroupSupport() {
if !config.IsMaster() {
return
}
c := cron.New()
//北京时间周一0点,过了一秒后,
spec := "1 0 0 * * 1"
_ = c.AddFunc(spec, func() {
defer utils.CheckGoPanic()
var model = domain.CreateModelNil()
//开始
model.Log.Infof("cron CalcGroupSupport start")
calcTime := time.Now().AddDate(0, 0, -1)
if err := group_s.NewGroupService(model.MyContext).GroupSupportResult(calcTime); err != nil {
model.Log.Errorf("cron CalcGroupSupport faild calcTime:%v, err:%v", calcTime, err)
return
}
model.Log.Infof("cron CalcGroupSupport after GroupSupportResult")
//全服发送H5
if err := sendGroupSupportH5(domain.CreateModelContext(model.MyContext)); err != nil {
model.Log.Errorf("cron CalcGroupSupport err:%v", err)
} else {
model.Log.Infof("cron CalcGroupSupport success")
}
})
c.Start()
}
func sendGroupSupportH5(model *domain.Model) error {
groupIds, err := group_m.GetAllGroupsSorted(model)
if err != nil {
return err
}
model.Log.Infof("SendGroupSupportH5 groupIds:%v", groupIds)
groupSupportH5 := group_m.GroupSupportH5{
CommonPublicMsg: group_m.CommonPublicMsg{
Type: group_e.GroupSupportH5,
},
H5: config.GetH5Config().GROUP_SUPPORT,
}
buffer, err := json.Marshal(groupSupportH5)
if err != nil {
model.Log.Errorf("publicScreenMsg AddSendGiftAsync json.Marshal(giftContent) err:%v", err)
return err
}
content := string(buffer)
//策略1:for循环,没有开启协程,100个停一下
for i, _ := range groupIds {
func(groupId string, content string) {
defer utils.CheckGoPanic()
model.Log.Infof("SendGroupSupportH5 groupId:%v", groupId)
txGroupId, err := group_m.ToTxGroupId(model, groupId)
// 公屏消息
if err == nil {
tencentyun.SendCustomMsg(model.Log, txGroupId, nil, content, "")
}
}(groupIds[i], content)
if i != 0 && i%100 == 0 {
//躺平1秒
time.Sleep(1 * time.Second)
}
}
return nil
}
// 群组扶持计算-旧数据
func CalcGroupSupport_OldData() {
if !config.IsMaster() {
return
}
c := cron.New()
spec := "0 27 10 29 8 ?"
_ = c.AddFunc(spec, func() {
defer utils.CheckGoPanic()
var model = domain.CreateModelNil()
//开始
model.Log.Infof("CalcGroupSupport_OldData start")
//beginTime, endTime, period := group_m.GetSupportLevelTime(time.Now().AddDate(0, 0, -group_e.SUPPORT_LEVEL_PERIOD_DAY))
beginTime, _, period := group_m.GetSupportLevelTime(time.Now())
endTime := time.Unix(1693275900, 0)
g := gift_m.GiftOperate{SceneType: gift_e.GroupSceneType, Model: model}
records, err := g.BatchGetConsumeByRange(beginTime, endTime)
if err != nil {
model.Log.Errorf("CalcGroupSupport_OldData beginTime:%v, endTime:%v, err:%v", beginTime, endTime, err)
return
}
// 流水写入redis
keyDiamond := rediskey.GetGroupSupportConsumeSummary(period)
for _, r := range records {
if r.SceneUid == "" || r.Consume <= 0 {
continue
}
_, err = model.RedisCluster.ZIncrBy(context.Background(), keyDiamond, float64(r.Consume), r.SceneUid).Result()
if err != nil {
model.Log.Errorf("CalcGroupSupport_OldData groupSupport key:%s, val:%d, member:%s, err:%v",
keyDiamond, r.Consume, r.SceneUid, err)
}
}
err = redisCli.SetExpire(model.RedisCluster, keyDiamond, time.Hour*24*14) // 保留两周
if err != nil {
model.Log.Errorf("CalcGroupSupport_OldData groupSupport key:%s, err:%v", keyDiamond, err)
return
}
// 支持者写入redis
for _, r := range records {
if r.SceneUid == "" || r.C <= 0 {
continue
}
// 支持者列表
support := gift_m.GiftOperate{SceneType: gift_e.GroupSceneType, SceneUid: r.SceneUid, Model: model}
uids, err := support.BatchGetSupportList(model, beginTime, endTime)
if err != nil {
model.Log.Errorf("CalcGroupSupport_OldData beginTime:%v, endTime:%v, imGroupId:%v, err:%v", beginTime, endTime, r.SceneUid, err)
continue
}
if len(uids) <= 0 {
continue
}
// 支持者数量
keySupportNum := rediskey.GetGroupSupportCountSupporter(period, r.SceneUid)
for _, uid := range uids {
err = model.RedisCluster.SAdd(context.Background(), keySupportNum, uid).Err()
if err != nil {
model.Log.Errorf("CalcGroupSupport_OldData groupSupport key:%s, UserId:%d, err:%v", keySupportNum, uid, err)
}
}
err = redisCli.SetExpire(model.RedisCluster, keySupportNum, time.Hour*24*14) // 保留两周
if err != nil {
model.Log.Errorf("AddSendGiftEventAsync groupSupport key:%s, err:%v", keySupportNum, err)
}
}
model.Log.Infof("CalcGroupSupport_OldData end")
})
c.Start()
}
package mic_cron
import (
"fmt"
"git.hilo.cn/hilo-common/domain"
"github.com/robfig/cron"
"hilo-group/_const/redis_key/mic_k"
"hilo-group/domain/cache/mic_c"
"hilo-group/domain/event/mic_ev"
"hilo-group/domain/model/group_m"
"hilo-group/domain/model/mic_m"
"hilo-group/domain/service/group_mic_s"
"time"
)
func OnMicCheck() {
c := cron.New()
//一分钟执行一次
spec := "30 */1 * * * ?"
_ = c.AddFunc(spec, func() {
//获取麦上的所有人
var model = domain.CreateModelNil()
groupIds, err := group_m.GetMicHasInGroups()
if err != nil {
model.Log.Errorf("cron micIn GetMicHasInGroups err:%v", err)
return
}
for _, groupId := range groupIds {
onGroupMicKey := mic_k.GetGroupOnMicUser(groupId) // 同步在mic上的人
//遍历每个麦位
for i := 1; i <= group_m.MaxMicNum; i++ {
micUser, err := group_m.GetMicUser(model, groupId, i)
if err != nil {
model.Log.Errorf("cron micIn group_m.GetMicUser err:%v", err)
}
if micUser != nil {
if err := mic_c.QueueOnMic(model, &mic_ev.OnMicEvent{
GroupUuid: micUser.GroupUuid,
I: micUser.I,
ExternalId: micUser.ExternalId,
UserId: micUser.UserId,
Forbid: micUser.Forbid,
Timestamp: micUser.Timestamp,
}); err != nil {
model.Log.Errorf("QueueOnMic fail:%v", err)
}
// 设置mic上的人
model.Redis.HSet(model, onGroupMicKey, i, micUser.UserId)
} else {
// 删除mic上的人
model.Redis.HDel(model, onGroupMicKey, fmt.Sprintf("%d", i))
}
}
}
})
c.Start()
}
func OnMicQueue() {
for i := 0; i < 4; i++ {
go func() {
for true {
model := domain.CreateModelNil()
if onMic := mic_c.BLPopQueueOnMic(model); onMic != nil {
start := time.Now()
// 群组上麦经验
if err := group_mic_s.NewGroupPowerService(model.MyContext).IncrGroupPowerOnMicExpAndTime(onMic.GroupUuid, onMic.UserId, onMic.Timestamp); err != nil {
model.Log.Errorf("cron micIn GroupPowerOnMicExp err:%v", err)
} else {
model.Log.Infof("cron micIn GroupPowerOnMicExp success, groupId:%v, userId:%v,cost:%vs", onMic.GroupUuid, onMic.UserId, time.Now().Sub(start).Seconds())
}
// 用户上麦
//if err := mic_m.IncrUserOnMic(model, onMic.UserId, onMic.Timestamp); err != nil {
//if err := mic_m.IncrUserOnMicV2(model, onMic.UserId); err != nil {
if err := mic_m.IncrUserOnMicV3(model, onMic.UserId); err != nil {
model.Log.Errorf("cron micIn IncrUserOnMic err:%v", err)
} else {
}
}
}
}()
}
}
package user_cron
import (
"git.hilo.cn/hilo-common/domain"
"github.com/robfig/cron"
"hilo-group/domain/cache/user_c"
)
// 加载数据到lru
func LoadSvipVipNoble() {
go user_c.LoadAllSvipVipNoble(domain.CreateModelNil()) // 启动先执行一次
c := cron.New()
spec := "0 */30 * * * ?"
_ = c.AddFunc(spec, func() {
model := domain.CreateModelNil()
user_c.LoadAllSvipVipNoble(model)
})
c.Start()
}
......@@ -22,7 +22,15 @@ type BillboardUserInfo struct {
Num uint64 `json:"num"`
}
func GetGroupTop3Consume(model *domain.Model, groupId string, myUserId uint64) ([]BillboardUserInfo, error) {
//榜单中用户信息
type GroupTop3ConsumeUser struct {
//用户基本信息
UserBase user_cv.TopConsumersUser `json:"userBase"`
//数值
Num uint64 `json:"num"`
}
func GetGroupTop3Consume(model *domain.Model, groupId string, myUserId uint64) ([]GroupTop3ConsumeUser, error) {
now := time.Now()
period := now.Format(utils.COMPACT_MONTH_FORMAT)
data, err := getGroupTop3Consume(period, groupId)
......@@ -59,7 +67,15 @@ func GetGroupTop3Consume(model *domain.Model, groupId string, myUserId uint64) (
ret, err := saveGroupTop3Consume(period, groupId, diamonds)
model.Log.Infof("GetGroupTop3Consume SAVE ret = %d, err: %v", ret, err)
return result, nil
list := make([]GroupTop3ConsumeUser, 0, len(result))
for _, v := range result {
list = append(list, GroupTop3ConsumeUser{
UserBase: user_cv.TopConsumersUser{Id: v.UserBase.Id, Avatar: v.UserBase.Avatar, ExternalId: v.UserBase.ExternalId, Nick: v.UserBase.Nick},
})
}
return list, nil
}
userIds := make([]uint64, 0)
......@@ -86,7 +102,15 @@ func GetGroupTop3Consume(model *domain.Model, groupId string, myUserId uint64) (
})
}
}
return result, nil
list := make([]GroupTop3ConsumeUser, 0, len(result))
for _, v := range result {
list = append(list, GroupTop3ConsumeUser{
UserBase: user_cv.TopConsumersUser{Id: v.UserBase.Id, Avatar: v.UserBase.Avatar, ExternalId: v.UserBase.ExternalId, Nick: v.UserBase.Nick},
})
}
return list, nil
}
func getGroupTop3Consume(period string, groupId string) (map[string]string, error) {
......
package diamond_cv
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql"
. "git.hilo.cn/hilo-common/utils"
"gorm.io/gorm"
"hilo-group/_const/enum/diamond_e"
"hilo-group/domain/model/bean_m"
"hilo-group/domain/model/diamond_m"
"hilo-group/myerr"
"strconv"
)
type CvDiamond struct {
......@@ -26,33 +20,6 @@ type CvDiamondBean struct {
BeanNum string `json:"beanNum"`
}
func GetDiamondBean(userId mysql.ID) (*CvDiamondBean, error) {
var diamondAccount diamond_m.DiamondAccount
err := mysql.Db.Where(&diamond_m.DiamondAccount{
UserId: userId,
}).First(&diamondAccount).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
diamondAccount = diamond_m.DiamondAccount{
DiamondNum: 0,
}
}
return nil, err
}
var beanAccount bean_m.BeanAccount
err = mysql.Db.Where(&bean_m.BeanAccount{
UserId: userId,
}).First(&beanAccount).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
beanAccount = bean_m.BeanAccount{
BeanNum: 0,
}
}
}
return &CvDiamondBean{DiamondNum: diamondAccount.DiamondNum, BeanNum: strconv.FormatFloat(float64(beanAccount.BeanNum)/100, 'f', 2, 64)}, nil
}
type CvDiamondDetail struct {
//1:增加 2:减少
......@@ -74,113 +41,4 @@ func GetDiamond(userId mysql.ID) (*CvDiamond, error) {
return nil, err
}
return &CvDiamond{DiamondNum: NumToUint32(&diamondAccount.DiamondNum), PinkDiamondNum: NumToUint32(&diamondAccount.PinkDiamondNum)}, nil
}
func GetDiamondBalances(userIds []mysql.ID) (map[mysql.ID]mysql.Num, error) {
result := make(map[mysql.ID]mysql.Num, len(userIds))
data := make([]diamond_m.DiamondAccount, 0)
err := mysql.Db.Where("user_id IN ?", userIds).Find(&data).Error
if err != nil {
return nil, err
}
for _, i := range data {
result[i.UserId] = i.DiamondNum
}
return result, nil
}
//充值记录
func GetDiamondBuyList(userId mysql.ID, pageSize int, pageIndex int) ([]*CvDiamondDetail, error) {
var diamondAccountDetails []diamond_m.DiamondAccountDetail
if err := mysql.Db.Model(&diamond_m.DiamondAccountDetail{}).
Where("user_id = ? AND operate_type in (?)", userId, []uint8{diamond_e.BuyDiamond, diamond_e.DealerTransfer, diamond_e.Checkout, diamond_e.PayerMax, diamond_e.Paypal}).
Order("id desc").Limit(pageSize).Offset((pageIndex - 1) * pageSize).Find(&diamondAccountDetails).Error; err != nil {
return nil, err
}
var cvDiamondDetails []*CvDiamondDetail
for i := 0; i < len(diamondAccountDetails); i++ {
unixTime := diamondAccountDetails[i].CreatedTime.Unix()
cvDiamondDetails = append(cvDiamondDetails, &CvDiamondDetail{
AddReduce: TypeToUint8(&diamondAccountDetails[i].AddReduce),
OperateType: TypeToUint8(&diamondAccountDetails[i].OperateType),
DiamondNum: NumToUint32(&diamondAccountDetails[i].Num),
CreatedTime: &unixTime,
})
}
return cvDiamondDetails, nil
}
//钻石明细,不包括充值
func GetDiamondDetailList(model *domain.Model, userId mysql.ID, pageSize int, pageIndex int) ([]*CvDiamondDetail, error) {
diamondAccountDetails := make([]*diamond_m.DiamondAccountDetail, 0)
offset := (pageIndex - 1) * pageSize
optList := []int{int(diamond_e.BuyDiamond), int(diamond_e.DealerTransfer), int(diamond_e.Checkout), int(diamond_e.PayerMax)}
details := make([]*diamond_m.DiamondAccountDetail, 0)
if offset == 0 { // 首页请求数据,获取 pageSize*3 条过滤返回
sql := "select * from diamond_account_detail where user_id = ? order by id desc limit ?"
if err := mysql.Db.WithContext(model).Raw(sql, userId, pageSize*3).Find(&details).Error; err != nil {
return nil, myerr.WrapErr(err)
}
notInMap := make(map[int]bool)
for _, v := range optList {
notInMap[v] = true
}
for _, v := range details {
if _, ok := notInMap[int(v.OperateType)]; !ok {
diamondAccountDetails = append(diamondAccountDetails, v)
}
}
if len(diamondAccountDetails) > pageSize {
diamondAccountDetails = diamondAccountDetails[:pageSize]
}
}
// 非首页,或者首页没取满 pageSize 条
if offset > 0 || (len(details) == pageSize*3 && len(diamondAccountDetails) < pageSize) {
diamondAccountDetails = make([]*diamond_m.DiamondAccountDetail, 0)
sql := "select * from diamond_account_detail where user_id = ? and operate_type not in (?) order by id desc limit ?,?"
if err := mysql.Db.WithContext(model).Raw(sql, userId, optList, offset, pageSize).
Find(&diamondAccountDetails).Error; err != nil {
return nil, myerr.WrapErr(err)
}
}
//if err := mysql.Db.Table("diamond_account_detail FORCE INDEX(Index_1)").
// Where("user_id = ? AND operate_type not in (?)", userId,
// []int{int(diamond_m2.BuyDiamond), int(diamond_m2.DealerTransfer), int(diamond_m2.Checkout), int(diamond_m2.PayerMax)}).
// Order("id desc").Limit(pageSize).Offset((pageIndex - 1) * pageSize).Find(&diamondAccountDetails).Error; err != nil {
// return nil, myerr.WrapErr(err)
//}
cvDiamondDetails := []*CvDiamondDetail{}
for i := 0; i < len(diamondAccountDetails); i++ {
unixTime := diamondAccountDetails[i].CreatedTime.Unix()
cvDiamondDetails = append(cvDiamondDetails, &CvDiamondDetail{
AddReduce: TypeToUint8(&diamondAccountDetails[i].AddReduce),
OperateType: TypeToUint8(&diamondAccountDetails[i].OperateType),
DiamondNum: NumToUint32(&diamondAccountDetails[i].Num),
CreatedTime: &unixTime,
})
}
return cvDiamondDetails, nil
}
//粉钻流水,包含充值
func GetPinkDiamondDetailList(userId mysql.ID, pageSize int, pageIndex int) ([]*CvDiamondDetail, error) {
var diamondAccountDetails []diamond_m.DiamondPinkAccountDetail
if err := mysql.Db.Model(&diamond_m.DiamondPinkAccountDetail{}).
Where("user_id = ?", userId).
Order("id desc").Limit(pageSize).Offset((pageIndex - 1) * pageSize).Find(&diamondAccountDetails).Error; err != nil {
return nil, myerr.WrapErr(err)
}
var cvDiamondDetails []*CvDiamondDetail
for i := 0; i < len(diamondAccountDetails); i++ {
unixTime := diamondAccountDetails[i].CreatedTime.Unix()
cvDiamondDetails = append(cvDiamondDetails, &CvDiamondDetail{
AddReduce: TypeToUint8(&diamondAccountDetails[i].AddReduce),
OperateType: TypeToUint8(&diamondAccountDetails[i].OperateType),
DiamondNum: NumToUint32(&diamondAccountDetails[i].Num),
CreatedTime: &unixTime,
})
}
return cvDiamondDetails, nil
}
}
\ No newline at end of file
This diff is collapsed.
......@@ -16,6 +16,7 @@ import (
"hilo-group/cv/user_cv"
"hilo-group/domain/model/groupPower_m"
"hilo-group/domain/model/group_m"
"hilo-group/domain/model/user_m"
"hilo-group/myerr"
"sort"
"strconv"
......@@ -232,28 +233,37 @@ func GetCvGroupPowerUsers(groupPowerId uint64) ([]mysql.ID, error) {
return usreIds, nil
}
func BatchGetGroupPower(db *gorm.DB, userIds []uint64) (map[uint64]uint64, map[uint64]string, error) {
// return userId->powerId userId->powerName userId->powerNameplate
func BatchGetGroupPower(db *gorm.DB, userIds []uint64) (map[uint64]uint64, map[uint64]string, map[uint64]string, map[uint64]groupPower_e.GroupPowerGrade, error) {
if len(userIds) <= 0 {
return nil, nil, nil
return nil, nil, nil, nil, nil
}
groupPowers, err := groupPower_m.GetGroupPowerMap(db, userIds)
if err != nil {
return nil, nil, err
return nil, nil, nil, nil, err
}
gpIds := make([]uint64, 0)
for _, i := range groupPowers {
gpIds = append(gpIds, i)
}
powerNames, err := groupPower_m.GetGroupPowerNames(db, gpIds)
powerNames, powerNameplates, err := groupPower_m.GetGroupPowerNames(db, gpIds)
if err != nil {
return nil, nil, err
return nil, nil, nil, nil, err
}
groupPowerGrade, err := groupPower_m.MGetGroupPowerGrade(domain.CreateModelNil(), gpIds)
if err != nil {
return nil, nil, nil, nil, err
}
groupPowerNames := make(map[mysql.ID]string, 0)
groupPowerNameplates := make(map[mysql.ID]string, 0)
groupPowerGrades := make(map[mysql.ID]groupPower_e.GroupPowerGrade, 0)
for i, g := range groupPowers {
groupPowerNames[i] = powerNames[g]
groupPowerNameplates[i] = powerNameplates[g]
groupPowerGrades[i] = groupPowerGrade[g].Grade
}
return groupPowers, groupPowerNames, nil
return groupPowers, groupPowerNames, groupPowerNameplates, groupPowerGrades, nil
}
//获取国家势力的所有用户数量
......@@ -639,3 +649,56 @@ func GetAllPowerDiamond(period string) (map[string]string, error) {
key := redis_key.GetPrefixGroupPowerDiamond(period)
return redisCli.GetRedis().HGetAll(context.Background(), key).Result()
}
type GroupPowerInfo struct {
Info *GroupPower `json:"info"`
Members []*GroupPowerUser `json:"members"`
Stars []*GroupPowerStar `json:"stars,omitempty"`
}
type GroupPower struct {
Id uint64 `json:"id"`
Name string `json:"name"`
Nameplate string `json:"nameplate"` // 铭牌
Declaration string `json:"declaration"` // 宣言
Icon string `json:"icon"` // 头像
Grade groupPower_e.GroupPowerGrade `json:"grade" gorm:"-"` // 等级
Exp mysql.Num `json:"exp" gorm:"-"` // 当前经验值
NextExp mysql.Num `json:"nextExp" gorm:"-"` // 升到下一级需要的经验值
GradeName mysql.Str `json:"gradeName"` // 等级称号
GradeMedal mysql.Str `json:"gradeMedal"` // 等级勋章图片
MemberNum mysql.Num `json:"memberNum" gorm:"-"` // 当前人数
MemberMax mysql.Num `json:"memberMax" gorm:"-"` // 最大人数
Role int `json:"role" gorm:"-"` // 我在此家族中的角色 0.路人 1.成员 2.家族长 3.管理员
IsApply bool `json:"isApply" gorm:"-"` // 最大人数
MonthRank int `json:"monthRank" gorm:"-"` // 家族月排名
}
type GroupPowerUser struct {
User *user_m.UserTiny `json:"user"`
Role groupPower_e.GroupPowerUserRole `json:"role"`
}
type GroupPowerStar struct {
User user_cv.CvUserTiny `json:"user"`
RankingType groupPower_e.GroupPowerRankType `json:"rankingType"`
}
type FamilyMemberDetail struct {
User user_cv.CvUserExtend `json:"user"`
Role groupPower_e.GroupPowerUserRole `json:"role"`
}
type FamilyApplyList struct {
User *user_m.UserTiny `json:"user"`
Time int64 `json:"time"`
Status int8 `json:"status"` // 0未操作,1已接受,2.已拒绝
MgrName string `json:"mgrName"` // 管理员名称
}
type FamilyQuitList struct {
User *user_m.UserTiny `json:"user"`
Time int64 `json:"time"`
QuitType int8 `json:"quitType"` // 1.主动退出 2.被踢出
MgrName string `json:"mgrName"` // 管理员名称
}
package group_power_cv
import (
"hilo-group/_const/enum/groupPower_e"
"hilo-group/cv/user_cv"
)
// 家族信息
type CvGroupPowerInfo struct {
CvGroupPowerBase `json:",inline"`
CvGroupPowerMember `json:",inline"`
CvGroupPowerGrade `json:",inline"`
}
// 家族基本信息
type CvGroupPowerBase struct {
Id uint64 `json:"id"` // 家族id
Icon string `json:"icon"` // 家族图片
Name string `json:"name"` // 家族名
Nameplate string `json:"nameplate"` // 铭牌
}
// 家族成员
type CvGroupPowerMember struct {
MemberNum uint32 `json:"memberNum"` // 当前成员数
MemberMax uint32 `json:"memberMax"` // 成员上限
}
// 家族等级
type CvGroupPowerGrade struct {
Grade groupPower_e.GroupPowerGrade `json:"grade"` // 等级 0:青铜 1:白银 2:黄金 3:黑金
Exp uint32 `json:"exp"` // 经验值
NextExp uint32 `json:"nextExp,omitempty"` // 下个等级所需经验值
ExpireAt string `json:"expireAt,omitempty"` // 有效期
}
// 家族榜单
type CvGroupPowerRank struct {
MyGroupPower *CvGroupPowerRankData `json:"myGroupPower,omitempty"` // 我的家族排名
Items []CvGroupPowerRankData `json:"items"` // 列表
}
// 家族月度排行活动榜单
type CvGroupPowerRankMontAct struct {
MyGroupPower *CvGroupPowerRankData `json:"myGroupPower"` // 我的家族排名
Items []CvGroupPowerRankData `json:"items"` // 列表
MyGroupPowerLast *CvGroupPowerRankData `json:"myGroupPowerLast"` // 我的家族排名(上月)
ItemsLast []CvGroupPowerRankData `json:"itemsLast"` // 列表(上月)
LeftSecond int64 `json:"leftSecond"` // 活动倒计时
}
type CvGroupPowerRankData struct {
CvGroupPowerBase `json:",inline"`
CvGroupPowerGrade `json:",inline"`
Rank int `json:"rank"` // 排名
StarList []*CvGroupPowerStarData `json:"starList"` // 家族贡献top10
}
// 家族之星
type CvGroupPowerStarData struct {
User user_cv.CvUserTiny `json:"user"`
Score uint32 `json:"score"` // 对应分值
}
// 资源等级
type CvResGrade struct {
Grade groupPower_e.GroupPowerGrade `json:"grade"` // 等级
}
// 特权信息
type CvPrivilege struct {
Type groupPower_e.GroupPowerPrivilege `json:"type"` // 特权id 1:成员数 2:管理员数 3:家族铭牌 4:家族徽章装饰 5:编辑铭牌 6:家族头饰
Num int `json:"num"` // 数目
Icon string `json:"icon"` // 图标
}
// 家族等级页
type CvGroupPowerGradeDetail struct {
GroupPowerBase CvGroupPowerBase `json:"groupPowerBase"` // 家族基本信息
GroupPowerGrade CvGroupPowerGrade `json:"groupPowerGrade"` // 家族等级信息
ResGradeList []CvResGrade `json:"resGradeList"` // 资源等级列表,青铜、白银、黄金、黑金
PrivilegeList []CvPrivilege `json:"privilegeList"` // 等级特权
IsMember bool `json:"isMember"` // 是否家族成员
}
var CvResGradeList = []CvResGrade{
{groupPower_e.GroupPowerGrade0},
{groupPower_e.GroupPowerGrade1},
{groupPower_e.GroupPowerGrade2},
{groupPower_e.GroupPowerGrade3},
}
var GroupPowerGradePrivilegeNum = map[groupPower_e.GroupPowerGrade][]CvPrivilege{
groupPower_e.GroupPowerGrade0: {
{groupPower_e.GroupPowerPrivilegeMemberNum, 300, "https://image.whoisamy.shop/hilo/resource/family/users.png"},
{groupPower_e.GroupPowerPrivilegeMgrNum, 10, "https://image.whoisamy.shop/hilo/resource/family/gl_user.png"},
{groupPower_e.GroupPowerPrivilegeNameplate, 1, "https://image.whoisamy.shop/hilo/resource/family/nameplate_black.png"},
{groupPower_e.GroupPowerPrivilegeMedal, 1, "https://image.whoisamy.shop/hilo/resource/family/privilege_black.png"},
},
groupPower_e.GroupPowerGrade1: {
{groupPower_e.GroupPowerPrivilegeMemberNum, 500, "https://image.whoisamy.shop/hilo/resource/family/users.png"},
{groupPower_e.GroupPowerPrivilegeMgrNum, 15, "https://image.whoisamy.shop/hilo/resource/family/gl_user.png"},
{groupPower_e.GroupPowerPrivilegeNameplate, 1, "https://image.whoisamy.shop/hilo/resource/family/nameplate_cyan.png"},
{groupPower_e.GroupPowerPrivilegeMedal, 1, "https://image.whoisamy.shop/hilo/resource/family/privilege_cyan.png"},
{groupPower_e.GroupPowerPrivilegeNameplateEdit, 1, "https://image.whoisamy.shop/hilo/resource/family/edit_cyan.png"},
},
groupPower_e.GroupPowerGrade2: {
{groupPower_e.GroupPowerPrivilegeMemberNum, 800, "https://image.whoisamy.shop/hilo/resource/family/users.png"},
{groupPower_e.GroupPowerPrivilegeMgrNum, 20, "https://image.whoisamy.shop/hilo/resource/family/gl_user.png"},
{groupPower_e.GroupPowerPrivilegeNameplate, 1, "https://image.whoisamy.shop/hilo/resource/family/nameplate_white.png"},
{groupPower_e.GroupPowerPrivilegeMedal, 1, "https://image.whoisamy.shop/hilo/resource/family/privilege_white.png"},
{groupPower_e.GroupPowerPrivilegeNameplateEdit, 1, "https://image.whoisamy.shop/hilo/resource/family/edit_white.png"},
{groupPower_e.GroupPowerPrivilegeNameplateHeadwear, 1, "https://image.whoisamy.shop/hilo/resource/family/headwear_white.png"},
},
groupPower_e.GroupPowerGrade3: {
{groupPower_e.GroupPowerPrivilegeMemberNum, 1200, "https://image.whoisamy.shop/hilo/resource/family/users.png"},
{groupPower_e.GroupPowerPrivilegeMgrNum, 25, "https://image.whoisamy.shop/hilo/resource/family/gl_user.png"},
{groupPower_e.GroupPowerPrivilegeNameplate, 1, "https://image.whoisamy.shop/hilo/resource/family/nameplate_yellow.png"},
{groupPower_e.GroupPowerPrivilegeMedal, 1, "https://image.whoisamy.shop/hilo/resource/family/privilege_yellow.png"},
{groupPower_e.GroupPowerPrivilegeNameplateEdit, 1, "https://image.whoisamy.shop/hilo/resource/family/edit_yellow.png"},
{groupPower_e.GroupPowerPrivilegeNameplateHeadwear, 1, "https://image.whoisamy.shop/hilo/resource/family/headwear_yellow.png"},
},
}
This diff is collapsed.
......@@ -11,6 +11,8 @@ MYSQL_DB=hilo_code
[REDIS]
REDIS_HOST=47.244.34.27:6379
REDIS_PASSWORD=8QZ9JD1zLvPR3yHf
REDIS_CLUSTER_HOST=47.244.34.27:6379
REDIS_CLUSTER_PASSWORD=8QZ9JD1zLvPR3yHf
[JWT]
SECRET=hilo1632
ISSUER_API=hiloApi
......@@ -72,6 +74,9 @@ APP_CERTIFICATE=ff29c100a613433db82324e8411eabc8
CUSTOMER_KEY=6b132c0ff7164560a2bc53fda06ea85a
CUSTOMER_SECRET=eedad2cd16d24834990d5450ace9f1ce
CALLBACK_SECRET=n_ZizS_N8
[TRTC]
APP_ID=1400548270
APP_CERTIFICATE=321bd60f73096b059c7350f1cd97d51028850b34fa58c5c0d26bb4a19e783de8
[CHECKOUT]
AUTHORIZATION=sk_test_9b5e771c-5a3f-4a8d-a4da-31b19bd43d83
URL=https://api.sandbox.checkout.com/hosted-payments
......@@ -114,6 +119,8 @@ NOBLE_BUY_IOS=https://h5.whoisamy.shop/action/hiloHtml/22_05_26_buy_nobility/pag
GUILD_DATA_URL=https://test.chathot.me/action/hiloHtml/22_10_18_app_data_coins/index.html
MGR_GUILD_DATA_URL=https://test.chathot.me/action/hiloHtml/22_10_18_app_data_coins/union.html
RANKING_PINK_DIAMOND_URL=https://test.chathot.me/action/activitiesPage/2022_10_17HiloLiveH5/index.html
AGENT_SHARE_URL=https://test.chathot.me/action/hiloHtml/22_05_30_recharge/topup.html?external_id=
AGENT_SHARE_ICON=https://image.whoisamy.shop/hilo/resource/user_transfer1.png
[GROUPIM]
MSG_SORT_EXPIRE=21600
MSG_SORT_SNAP=300
......
......@@ -9,15 +9,18 @@ import (
)
type gameAutoJoinMsg struct {
TraceId string
Token string
EnterType string
GameCode string
TraceId string
Token string
EnterType string
GameCode string
Is1V1 string
GameMode string
Is1V1Robot string
}
func SetAutoMathEnterRoom(userId uint64, imGroupId, traceId, token, enterType, gameCode string) error {
func SetAutoMathEnterRoom(userId uint64, imGroupId, traceId, token, enterType, gameCode, is1V1, gameMode, is1V1Robot string) error {
key := game_e.GetAutoMathEnterRoom(userId, imGroupId)
info := gameAutoJoinMsg{traceId, token, enterType, gameCode}
info := gameAutoJoinMsg{traceId, token, enterType, gameCode, is1V1, gameMode, is1V1Robot}
data, err := json.Marshal(info)
if err != nil {
return err
......@@ -26,7 +29,7 @@ func SetAutoMathEnterRoom(userId uint64, imGroupId, traceId, token, enterType, g
if err != nil {
return err
}
redisCli.GetRedis().Expire(context.Background(), key, time.Second*3)
redisCli.GetRedis().Expire(context.Background(), key, time.Second*10)
return nil
}
......
package gift_c
import (
"encoding/json"
"git.hilo.cn/hilo-common/domain"
"github.com/go-redis/redis/v8"
"hilo-group/domain/event/gift_ev"
"time"
)
const EventSendGiftHiloGroupQueue = "send:gift:queue:hilo_group"
// redis pop event sendGift
func BLPopQueueSendGift(model *domain.Model) *gift_ev.SendGiftEvent {
var res *gift_ev.SendGiftEvent
queue := EventSendGiftHiloGroupQueue
strs, err := model.RedisCluster.BLPop(model, time.Second, queue).Result()
if err != nil {
if err != redis.Nil {
model.Log.Errorf("BLPopQueueSendGift fail:%v", err)
}
return nil
}
if len(strs) >= 2 {
content := strs[1]
res = new(gift_ev.SendGiftEvent)
if err := json.Unmarshal([]byte(content), res); err != nil {
model.Log.Errorf("BLPopQueueSendGift json fail:%v", err)
return nil
}
return res
}
return nil
}
package groupPower_c
import (
"fmt"
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql"
"github.com/go-redis/redis/v8"
"github.com/jinzhu/now"
"github.com/pkg/errors"
"github.com/spf13/cast"
"hilo-group/_const/enum/groupPower_e"
"hilo-group/_const/redis_key/groupPower_k"
"time"
)
// 家族之星-排名
type GroupPowerStarRank struct {
Period string
GroupPowerId mysql.ID
UserId mysql.ID
Type groupPower_e.GroupPowerStarType
Score mysql.Num
}
// 增加家族之星分数
func IncrGroupPowerDayStarScore(model *domain.Model, groupPowerId, userId mysql.ID, _type groupPower_e.GroupPowerStarType, score mysql.Num) error {
ttl := map[string]time.Duration{
"day": time.Hour * 24 * 7,
"week": time.Hour * 24 * 7 * 30,
"month": time.Hour * 24 * 7 * 30 * 2,
}
for _, period := range []string{"day", "week", "month"} {
date := ""
switch period {
case "day":
date = time.Now().Format("2006-01-02")
case "week":
date = now.BeginningOfWeek().Format("2006-01-02")
case "month":
date = now.BeginningOfMonth().Format("2006-01-02")
}
key := groupPower_k.GetGroupPowerStarRankKey(_type, period, groupPowerId, date)
model.RedisCluster.ZIncrBy(model, key, float64(score), fmt.Sprintf("%d", userId))
model.RedisCluster.Expire(model, key, ttl[period])
}
return nil
}
// 获取家族之星排行
// param period: day|week|month
func GetGroupPowerStarRankPeriod(model *domain.Model, period string, groupPowerId mysql.ID, _type groupPower_e.GroupPowerStarType, offset, limit int, targetDate ...string) ([]*GroupPowerStarRank, error) {
var res []*GroupPowerStarRank
date := ""
switch period {
case "day":
date = time.Now().Format("2006-01-02")
case "week":
date = now.BeginningOfWeek().Format("2006-01-02")
case "month":
date = now.BeginningOfMonth().Format("2006-01-02")
}
if len(date) <= 0 {
return res, errors.New("illegal date")
}
if len(targetDate) > 0 {
date = targetDate[0]
}
key := groupPower_k.GetGroupPowerStarRankKey(_type, period, groupPowerId, date)
rows, err := model.RedisCluster.ZRevRangeByScoreWithScores(model, key, &redis.ZRangeBy{
Min: "-inf",
Max: "+inf",
Offset: int64(offset),
Count: int64(limit),
}).Result()
if err != nil {
model.Log.Errorf("GetGroupPowerStarRankPeriod fail:%v", err)
return res, err
}
for _, v := range rows {
res = append(res, &GroupPowerStarRank{
Period: period,
GroupPowerId: groupPowerId,
UserId: cast.ToUint64(v.Member),
Type: _type,
Score: mysql.Num(v.Score),
})
}
return res, nil
}
// 获取家族之星三个排行榜的各自第一名
func GetGroupPowerMonthStartTop1(model *domain.Model, groupPowerId mysql.ID) ([]*GroupPowerStarRank, error) {
var res []*GroupPowerStarRank
r1, err := GetGroupPowerStarRankPeriod(model, "month", groupPowerId, groupPower_e.GroupPowerStarTypeFamous, 0, 1)
if err != nil {
return res, err
}
r2, err := GetGroupPowerStarRankPeriod(model, "month", groupPowerId, groupPower_e.GroupPowerStarTypeActive, 0, 1)
if err != nil {
return res, err
}
r3, err := GetGroupPowerStarRankPeriod(model, "month", groupPowerId, groupPower_e.GroupPowerStarTypeCharm, 0, 1)
if err != nil {
return res, err
}
res = append(res, r1...)
res = append(res, r2...)
res = append(res, r3...)
return res, nil
}
package group_c
import (
"fmt"
"git.hilo.cn/hilo-common/domain"
"github.com/go-redis/redis/v8"
"github.com/spf13/cast"
"hilo-group/_const/redis_key/group_k"
"strconv"
"time"
)
// 用户进房
func ZAddUserEnterRoom(model *domain.Model, userId uint64, imGroupId string) {
userKey := group_k.GetUserEnterRoomUserKey(userId)
groupKey := group_k.GetUserEnterRoomGroupKey(imGroupId)
if err := model.Redis.ZAdd(model, userKey, &redis.Z{
Score: float64(time.Now().Unix()),
Member: imGroupId,
}).Err(); err != nil {
model.Log.Errorf("ZAddUserEnterRoom user fail:%v", err)
}
if err := model.Redis.ZAdd(model, groupKey, &redis.Z{
Score: float64(time.Now().Unix()),
Member: userId,
}).Err(); err != nil {
model.Log.Errorf("ZAddUserEnterRoom room fail:%v", err)
}
}
// 获取最近房间访客
// 15天
func GetLastRoomVisitors(model *domain.Model, imGroupId string) (userIds []uint64) {
groupKey := group_k.GetUserEnterRoomGroupKey(imGroupId)
res, err := model.Redis.ZRangeByScore(model, groupKey, &redis.ZRangeBy{
Min: fmt.Sprintf("%d", time.Now().AddDate(0, 0, -15).Unix()),
Max: "+inf",
}).Result()
if err != nil {
return
}
for _, u := range res {
uid, _ := strconv.ParseUint(u, 10, 64)
if uid > 0 {
userIds = append(userIds, uid)
}
}
return
}
// 获取最近进入的房间
// 3个月
func GetUserRecentRooms(model *domain.Model, userId uint64, offset, limit int64) (imGroupIds []string, roomEnterTime map[string]int64) {
roomEnterTime = make(map[string]int64)
userKey := group_k.GetUserEnterRoomUserKey(userId)
res, err := model.Redis.ZRevRangeByScoreWithScores(model, userKey, &redis.ZRangeBy{
Min: fmt.Sprintf("%d", time.Now().AddDate(0, -3, 0).Unix()),
Max: "+inf",
Offset: offset,
Count: limit,
}).Result()
if err != nil {
return
}
for _, v := range res {
imGroupId := cast.ToString(v.Member)
imGroupIds = append(imGroupIds, imGroupId)
roomEnterTime[imGroupId] = int64(v.Score)
}
return
}
// 清理房间访客
// 15天前访问的
func RemoveRoomVisitors(model *domain.Model, imGroupId string) {
groupKey := group_k.GetUserEnterRoomGroupKey(imGroupId)
n, err := model.Redis.ZRemRangeByScore(model, groupKey, "-inf", fmt.Sprintf("%d", time.Now().AddDate(0, 0, -15).Unix())).Result()
if err != nil {
model.Log.Errorf("RemoveRoomVisitors fail:%v", err)
} else {
model.Log.Infof("RemoveRoomVisitors key:%v,n:%v", groupKey, n)
}
}
......@@ -14,6 +14,10 @@ import (
"time"
)
func init() {
group_m.FuncAddEditGroupCd = AddEditGroupCd
}
func GetGroupMemberCount(groupId string) (int, error) {
key := redis_key.GetGroupMemCountKey(groupId)
return redisCli.RedisClient.Get(context.Background(), key).Int()
......@@ -79,17 +83,17 @@ func SetGroupMemberTTL(groupId string, ttl time.Duration) (bool, error) {
func GetGroupConsume(groupId string) (uint64, error) {
key := getGroupConsumeKey(groupId)
return redisCli.RedisClient.Get(context.Background(), key).Uint64()
return redisCli.RedisClusterClient.Get(context.Background(), key).Uint64()
}
func SetGroupConsume(groupId string, consume uint64, ttl time.Duration) error {
key := getGroupConsumeKey(groupId)
return redisCli.RedisClient.Set(context.Background(), key, consume, ttl).Err()
return redisCli.RedisClusterClient.Set(context.Background(), key, consume, ttl).Err()
}
func ClearGroupConsume(groupId string) error {
key := getGroupConsumeKey(groupId)
return redisCli.RedisClient.Del(context.Background(), key).Err()
return redisCli.RedisClusterClient.Del(context.Background(), key).Err()
}
// 增加编辑用户cd
......
package mic_c
import (
"encoding/json"
"git.hilo.cn/hilo-common/domain"
"github.com/go-redis/redis/v8"
"hilo-group/_const/redis_key/mic_k"
"hilo-group/domain/event/mic_ev"
"time"
)
// redis queue on mic
func QueueOnMic(model *domain.Model, onMic *mic_ev.OnMicEvent) error {
queue := mic_k.GetOnMicQueue()
onMic.Ts = time.Now().UnixNano() // 给一个时间戳
body, _ := json.Marshal(onMic)
return model.RedisCluster.RPush(model, queue, string(body)).Err()
}
// redis pop on mic
func BLPopQueueOnMic(model *domain.Model) *mic_ev.OnMicEvent {
var res *mic_ev.OnMicEvent
queue := mic_k.GetOnMicQueue()
strs, err := model.RedisCluster.BLPop(model, time.Second, queue).Result()
if err != nil {
if err != redis.Nil {
model.Log.Errorf("BLPopQueueOnMic fail:%v", err)
}
return nil
}
if len(strs) >= 2 {
content := strs[1]
res = new(mic_ev.OnMicEvent)
if err := json.Unmarshal([]byte(content), res); err != nil {
model.Log.Errorf("BLPopQueueOnMic json fail:%v", err)
return nil
}
return res
}
return nil
}
......@@ -27,17 +27,17 @@ func SetJSON(model *domain.Model, key string, obj interface{}) (err error) {
if err != nil {
return err
}
return model.Redis.Set(model.Context, key, value, DEFAULT_TTL).Err()
return model.RedisCluster.Set(model.Context, key, value, DEFAULT_TTL).Err()
}
// 获取redis中json结构体
// return err: may redisV8.Nil
func GetJSON(model *domain.Model, key string, obj interface{}) (err error) {
var value []byte
defer func() {
model.Log.Infof("GetJson key:%v,value:%s,obj:%v,err:%v", key, value, obj, err)
}()
value, err = model.Redis.Get(model.Context, key).Bytes()
//defer func() {
// model.Log.Infof("GetJson key:%v,value:%s,obj:%v,err:%v", key, value, obj, err)
//}()
value, err = model.RedisCluster.Get(model.Context, key).Bytes()
if err != nil {
// may redisV2.Nil
return
......@@ -59,7 +59,7 @@ func TryLock(model *domain.Model, key string, acquireTimeout, expireTimeout time
if time.Now().After(deadline) {
return false
}
flag, err := model.Redis.SetNX(model, key, "1", expireTimeout).Result()
flag, err := model.RedisCluster.SetNX(model, key, "1", expireTimeout).Result()
if err != nil || !flag {
time.Sleep(time.Millisecond * 10)
} else {
......@@ -70,5 +70,5 @@ func TryLock(model *domain.Model, key string, acquireTimeout, expireTimeout time
// 解锁
func UnLock(model *domain.Model, key string) {
model.Redis.Del(model, key)
model.RedisCluster.Del(model, key)
}
package res_c
import (
"context"
"git.hilo.cn/hilo-common/domain"
"hilo-group/_const/redis_key"
"github.com/bluele/gcache"
"hilo-group/domain/model/res_m"
"time"
)
// 统一改成lru
var countryIconLru = gcache.New(1000).LRU().Build()
var countryIconKey = "country:icon"
var countryAreaLru = gcache.New(1000).LRU().Build()
var countryAreaKey = "country:area"
func GetCountryIconMap(model *domain.Model) (map[string]string, error) {
m, err := GetAllCountryIcon(model)
if err != nil || len(m) <= 0 {
......@@ -24,15 +30,54 @@ func GetCountryIconMap(model *domain.Model) (map[string]string, error) {
}
func GetAllCountryIcon(model *domain.Model) (map[string]string, error) {
key := redis_key.GetCountryIconKey()
return model.Redis.HGetAll(context.Background(), key).Result()
//key := redis_key.GetCountryIconKey()
if data, err := countryIconLru.Get(countryIconKey); err == nil {
return data.(map[string]string), nil
}
//return model.Redis.HGetAll(context.Background(), key).Result()
return map[string]string{}, nil
}
func SaveAllCountryIcon(model *domain.Model, icons map[string]string) {
//key := redis_key.GetCountryIconKey()
//ret, err := model.Redis.HSet(context.Background(), key, icons).Result()
//if err == nil {
// model.Redis.Expire(context.Background(), key, time.Minute*10)
//}
//return ret, err
_ = countryIconLru.SetWithExpire(countryIconKey, icons, time.Minute*10)
}
func GetCountryAreaMap(model *domain.Model) (map[string]string, error) {
m, err := GetAllCountryArea(model)
if err != nil || len(m) <= 0 {
m, err = res_m.GetAllCountriesArea(model)
if err != nil {
return nil, err
}
if len(m) <= 0 {
return map[string]string{}, nil
}
SaveAllCountryArea(model, m)
}
return m, nil
}
func SaveAllCountryIcon(model *domain.Model, icons map[string]string) (int64, error) {
key := redis_key.GetCountryIconKey()
ret, err := model.Redis.HSet(context.Background(), key, icons).Result()
if err == nil {
model.Redis.Expire(context.Background(), key, time.Minute*10)
func GetAllCountryArea(model *domain.Model) (map[string]string, error) {
//key := redis_key.GetCountryAreaKey()
//return model.Redis.HGetAll(context.Background(), key).Result()
if data, err := countryAreaLru.Get(countryAreaKey); err == nil {
return data.(map[string]string), nil
}
return ret, err
return map[string]string{}, nil
}
func SaveAllCountryArea(model *domain.Model, data map[string]string) {
//key := redis_key.GetCountryAreaKey()
//ret, err := model.Redis.HSet(context.Background(), key, data).Result()
//if err == nil {
// model.Redis.Expire(context.Background(), key, time.Minute*10)
//}
//return ret, err
_ = countryAreaLru.SetWithExpire(countryAreaKey, data, time.Minute*10)
}
......@@ -2,42 +2,44 @@ package room_c
import (
"context"
"errors"
"fmt"
"git.hilo.cn/hilo-common/mylogrus"
"git.hilo.cn/hilo-common/resource/config"
"git.hilo.cn/hilo-common/resource/redisCli"
"github.com/bluele/gcache"
redis2 "github.com/go-redis/redis/v8"
"github.com/spf13/cast"
"hilo-group/_const/redis_key"
"strconv"
"hilo-group/_const/redis_key/group_k"
"time"
)
// 处理访问房间的相关缓存
func ProcessRoomVisit(groupId string, userId uint64) error {
key := redis_key.GetPrefixGroupInUserDuration(groupId)
now := time.Now()
ret, err := redisCli.GetRedis().ZAdd(context.Background(), key, &redis2.Z{
Score: float64(now.Unix()),
Member: userId,
}).Result()
if err != nil {
return err
}
mylogrus.MyLog.Infof("ProcessRoomVisit, ZADD %s, return %d", key, ret)
// 每群定时清一次数据可以了
if now.Second()%redis_key.GroupInDurationClearPeriod == 0 {
rc, err := clearRoomVisit(groupId, now.AddDate(0, 0, -redis_key.GroupInDurationTTL))
if err == nil {
mylogrus.MyLog.Infof("ProcessRoomVisit, clearRoomVisit %s, return %d", key, rc)
} else {
mylogrus.MyLog.Warnf("ProcessRoomVisit, clearRoomVisit %s, failed %s", key, err.Error())
}
}
//key := redis_key.GetPrefixGroupInUserDuration(groupId)
//now := time.Now()
//ret, err := redisCli.GetRedis().ZAdd(context.Background(), key, &redis2.Z{
// Score: float64(now.Unix()),
// Member: userId,
//}).Result()
//if err != nil {
// return err
//}
//mylogrus.MyLog.Infof("ProcessRoomVisit, ZADD %s, return %d", key, ret)
//
//// 每群定时清一次数据可以了
//if now.Second()%redis_key.GroupInDurationClearPeriod == 0 {
// rc, err := clearRoomVisit(groupId, now.AddDate(0, 0, -redis_key.GroupInDurationTTL))
// if err == nil {
// mylogrus.MyLog.Infof("ProcessRoomVisit, clearRoomVisit %s, return %d", key, rc)
// } else {
// mylogrus.MyLog.Warnf("ProcessRoomVisit, clearRoomVisit %s, failed %s", key, err.Error())
// }
//}
// 马上更新roomVisitCount
if _, err := GetSetRoomVisitCount(groupId); err != nil {
mylogrus.MyLog.Warnf("ProcessRoomVisit, failed for key %s, err: %s", key, err.Error())
mylogrus.MyLog.Errorf("ProcessRoomVisit, failed for groupId %s, err: %s", groupId, err.Error())
}
return nil
......@@ -59,15 +61,17 @@ func ProcessUserRoomVisit(userId uint64, groupId string) error {
}
// 查询用户访问过的房间及其时间
// todo 去掉查询,redis性能
func GetUserRoomVisit(userId uint64) (map[string]int64, error) {
result := make(map[string]int64, 0)
return result, nil
key := redis_key.GetUserEnterRoomKey(userId)
ret, err := redisCli.GetRedis().ZRangeWithScores(context.Background(), key, 0, -1).Result()
if err != nil {
return nil, err
}
mylogrus.MyLog.Infof("GetUserRoomVisit, ZRangeWithScores %s, return %v", key, ret)
//mylogrus.MyLog.Infof("GetUserRoomVisit, ZRangeWithScores %s, return %v", key, ret)
result := make(map[string]int64, 0)
for _, i := range ret {
result[i.Member.(string)] = int64(i.Score)
}
......@@ -75,53 +79,63 @@ func GetUserRoomVisit(userId uint64) (map[string]int64, error) {
}
// 批量获取房间访问人数
// 带上lru
var roomVisitCountLru = gcache.New(100).LRU().Build()
func MGetRoomVisitCount(groupIds []string) (map[string]string, error) {
key := redis_key.GetPrefixRoomVisitCount()
visit := make(map[string]string)
if len(groupIds) <= 0 {
return visit, nil
}
res, err := redisCli.GetRedis().HMGet(context.Background(), key, groupIds...).Result()
lKey := "room:visit:count"
if data, err := roomVisitCountLru.Get(lKey); err == nil {
return data.(map[string]string), nil
}
// 用redisCluster中的zset代替,只是取出大于10的
zKey := redis_key.GetPrefixRoomVisitCountZset()
cnt := 10
if !config.AppIsRelease() {
cnt = 0
}
zRes, err := redisCli.GetClusterRedis().ZRevRangeByScoreWithScores(context.Background(), zKey, &redis2.ZRangeBy{
Min: fmt.Sprintf("%d", cnt),
Max: "+inf",
}).Result()
if err != nil {
mylogrus.MyLog.Errorf("MGetRoomVisitCount zset fail:%v", err)
return visit, err
}
if len(res) != len(groupIds) {
return visit, errors.New(fmt.Sprintf("MGetRoomVisitCount fail,miss match len,%v-%v", len(res), len(groupIds)))
}
for i, groupId := range groupIds {
if cnt, ok := res[i].(string); ok {
visit[groupId] = cnt
}
for _, v := range zRes {
visit[cast.ToString(v.Member)] = cast.ToString(v.Score)
}
_ = roomVisitCountLru.SetWithExpire(lKey, visit, time.Minute*15)
return visit, nil
}
func GetSetRoomVisitCount(groupId string) (int64, error) {
key := redis_key.GetPrefixGroupInUserDuration(groupId)
//key := redis_key.GetPrefixGroupInUserDuration(groupId)
key := group_k.GetUserEnterRoomGroupKey(groupId)
vc, err := redisCli.GetRedis().ZCard(context.Background(), key).Result()
// 查到合法值后,更新二级缓存
if err == nil && vc >= 0 {
ret, err := saveRoomVisitCount(groupId, vc)
mylogrus.MyLog.Infof("saveRoomVisitCount %s, ret = %d, err: %v", groupId, ret, err)
if err := saveRoomVisitCount(groupId, vc); err != nil {
mylogrus.MyLog.Errorf("saveRoomVisitCount %s, err: %v", groupId, err)
}
}
return vc, err
}
func saveRoomVisitCount(groupId string, count int64) (int64, error) {
key := redis_key.GetPrefixRoomVisitCount()
return redisCli.GetRedis().HSet(context.Background(), key, groupId, strconv.FormatInt(count, 10)).Result()
}
func clearRoomVisit(groupId string, t time.Time) (int64, error) {
value := strconv.FormatInt(t.Unix(), 10)
ret, err := redisCli.GetRedis().ZRemRangeByScore(context.Background(), redis_key.GetPrefixGroupInUserDuration(groupId), "0", value).Result()
if err != nil {
return 0, err
func saveRoomVisitCount(groupId string, count int64) error {
//key := redis_key.GetPrefixRoomVisitCount()
zKey := redis_key.GetPrefixRoomVisitCountZset()
// zset同步存一份到redis集群
if err := redisCli.GetClusterRedis().ZAdd(context.Background(), zKey, &redis2.Z{
Score: float64(count),
Member: groupId,
}).Err(); err != nil {
mylogrus.MyLog.Errorf("GetPrefixRoomVisitCountZset fail %s", err.Error())
return err
}
return ret, nil
}
func GetAllRoomVisitCount() (map[string]string, error) {
key := redis_key.GetPrefixRoomVisitCount()
return redisCli.GetRedis().HGetAll(context.Background(), key).Result()
return nil
//return redisCli.GetRedis().HSet(context.Background(), key, groupId, strconv.FormatInt(count, 10)).Result()
}
package user_c
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql"
"sync"
"time"
)
type UserLevel struct {
UserId mysql.ID
Level int
}
var svipVipNobleLock sync.RWMutex
var svipLevel = make(map[mysql.ID]int) // userId->svipLevel
var nobleLevel = make(map[mysql.ID]uint16) // userId->nobleLevel
var userVips = make(map[mysql.ID]bool) // userId->isVip
// 加载数据到lru
func LoadAllSvipVipNoble(model *domain.Model) {
start := time.Now()
var svips []UserLevel
svipMap := make(map[mysql.ID]int)
if err := model.DB().Table("user_svip").Select("user_id,level").Where("level > 0").Find(&svips).Error; err != nil {
model.Log.Errorf("LoadAllSvip fail:%v", err)
} else {
for _, v := range svips {
svipMap[v.UserId] = v.Level
}
}
var nobles []UserLevel
nobleMap := make(map[mysql.ID]uint16)
if err := model.DB().Table("user_noble").Select("user_id,MAX(level) level").
Where("level > 0 AND end_time > ?", time.Now()).Group("user_id").Find(&nobles).Error; err != nil {
model.Log.Errorf("LoadAllNoble fail:%v", err)
} else {
for _, v := range nobles {
nobleMap[v.UserId] = uint16(v.Level)
}
}
var vips []UserLevel
vipMap := make(map[mysql.ID]bool)
if err := model.DB().Table("user_vip").Select("user_id").
Where("expire_at > ?", time.Now()).Find(&vips).Error; err != nil {
model.Log.Errorf("LoadAllVip fail:%v", err)
} else {
for _, v := range vips {
vipMap[v.UserId] = true
}
}
// 上锁赋值
svipVipNobleLock.Lock()
svipLevel = svipMap
nobleLevel = nobleMap
userVips = vipMap
svipVipNobleLock.Unlock()
model.Log.Infof("LoadAllSvipVipNoble svip:%v,vip:%v,noble:%v,cost:%vs", len(svipMap), len(vipMap), len(nobleMap), time.Now().Sub(start).Seconds())
}
func BatchGetNobleLevel(model *domain.Model, userIds []uint64) map[uint64]uint16 {
res := make(map[uint64]uint16)
svipVipNobleLock.RLock()
defer svipVipNobleLock.RUnlock()
for _, userId := range userIds {
res[userId] = nobleLevel[userId]
}
return res
}
func MGetUserSvipLevel(model *domain.Model, userIds []uint64) map[uint64]int {
res := make(map[uint64]int)
svipVipNobleLock.RLock()
defer svipVipNobleLock.RUnlock()
for _, userId := range userIds {
res[userId] = svipLevel[userId]
}
return res
}
func BatchGetVips(model *domain.Model, userIds []uint64) map[uint64]*int64 {
res := make(map[uint64]*int64)
svipVipNobleLock.RLock()
defer svipVipNobleLock.RUnlock()
for _, userId := range userIds {
vip := int64(1)
if userVips[userId] {
res[userId] = &vip
}
}
return res
}
......@@ -6,10 +6,12 @@ import (
redisV8 "github.com/go-redis/redis/v8"
"github.com/jinzhu/copier"
"hilo-group/_const/redis_key/user_k"
"hilo-group/common"
"hilo-group/domain/cache"
"hilo-group/domain/model/user_m"
"hilo-group/myerr"
"hilo-group/myerr/bizerr"
"time"
)
// 获取用户简要信息
......@@ -36,6 +38,36 @@ func GetUserTinyById(model *domain.Model, userId mysql.ID) (*user_m.UserTiny, er
return userTiny, nil
}
// 获取用户简要信息
// param userId 用户id
func MGetUserTinyById(model *domain.Model, userIds []mysql.ID) []*user_m.UserTiny {
var users []*user_m.UserTiny
for _, userId := range userIds {
if user, _ := GetUserTinyById(model, userId); user != nil {
users = append(users, user)
}
}
return users
}
// 获取用户externalIds
// return []externalIds map[userId]extId map[userId]code
func GetUserExternalIds(model *domain.Model, userIds []mysql.ID) ([]string, map[uint64]string, map[uint64]string) {
var res []string
var m = make(map[uint64]string)
var c = make(map[uint64]string)
if len(userIds) <= 0 {
return res, m, c
}
users := MGetUserTinyById(model, userIds)
for _, u := range users {
res = append(res, u.ExternalId)
m[u.ID] = u.ExternalId
c[u.ID] = u.Code
}
return res, m, c
}
// 获取用户简要信息By ExternalId
func GetUserByExternalId(model *domain.Model, externalId mysql.Str) (*user_m.UserTiny, error) {
userId, err := ToUserId(model, externalId)
......@@ -50,7 +82,7 @@ func ToUserId(model *domain.Model, externalId mysql.Str) (mysql.ID, error) {
if externalId == "" {
return 0, myerr.NewSysError("externalId 不能为空")
}
userId, err := model.Redis.Get(model.Context, user_k.GetExternalIdToUidKey(externalId)).Int64()
userId, err := model.RedisCluster.Get(model.Context, user_k.GetExternalIdToUidKey(externalId)).Int64()
if err != nil && err != redisV8.Nil {
return 0, err
}
......@@ -73,7 +105,7 @@ func ToUserIdByCode(model *domain.Model, code mysql.Str) (mysql.ID, error) {
if code == "" {
return 0, myerr.NewSysError("code 不能为空")
}
userId, err := model.Redis.Get(model.Context, user_k.GetCodeToUidKey(code)).Int64()
userId, err := model.RedisCluster.Get(model.Context, user_k.GetCodeToUidKey(code)).Int64()
if err != nil && err != redisV8.Nil {
return 0, err
}
......@@ -96,16 +128,17 @@ func ToUserIdByCode(model *domain.Model, code mysql.Str) (mysql.ID, error) {
// 顺手缓存code->userId
// param user: 已经在上层获取的db User结构
func cacheUserTiny(model *domain.Model, user *user_m.User) error {
userTiny := new(user_m.UserTiny)
if err := copier.Copy(userTiny, user); err != nil {
return err
}
userTiny := ToUserTinyBy(user)
//userTiny := new(user_m.UserTiny)
//if err := copier.Copy(userTiny, user); err != nil {
// return err
//}
// cache externalId->userId
if err := model.Redis.SetEX(model.Context, user_k.GetExternalIdToUidKey(user.ExternalId), user.ID, cache.GetDefaultTTL()).Err(); err != nil {
if err := model.RedisCluster.SetEX(model.Context, user_k.GetExternalIdToUidKey(user.ExternalId), user.ID, cache.GetDefaultTTL()).Err(); err != nil {
return err
}
// cache code->userId
if err := model.Redis.SetEX(model.Context, user_k.GetCodeToUidKey(user.Code), user.ID, cache.GetDefaultTTL()).Err(); err != nil {
if err := model.RedisCluster.SetEX(model.Context, user_k.GetCodeToUidKey(user.Code), user.ID, cache.GetDefaultTTL()).Err(); err != nil {
return err
}
if err := cache.SetJSON(model, user_k.GetUserTinyKey(user.ID), userTiny); err != nil {
......@@ -113,3 +146,89 @@ func cacheUserTiny(model *domain.Model, user *user_m.User) error {
}
return nil
}
// 获取用户简要信息
// param userIds 用户id列表
func GetUserTinyMap(model *domain.Model, userIds []mysql.ID, isDefAvatar bool) (map[mysql.ID]*user_m.UserTiny, error) {
redisNoIds := make([]mysql.ID, 0)
res := make(map[mysql.ID]*user_m.UserTiny)
for _, id := range userIds {
userTiny := new(user_m.UserTiny)
key := user_k.GetUserTinyKey(id)
err := cache.GetJSON(model, key, userTiny)
if err != nil && err != redisV8.Nil {
return nil, err
}
if err == redisV8.Nil {
redisNoIds = append(redisNoIds, id)
} else if userTiny.ID > 0 {
res[id] = userTiny
}
}
// 从db中读
users, err := user_m.GetUsers(model, redisNoIds)
if err != nil {
return nil, err
}
for _, u := range users {
userTiny := ToUserTinyBy(u)
err = cacheUserTiny(model, u)
if err != nil {
return nil, err
}
res[userTiny.ID] = userTiny
}
if isDefAvatar {
for _, v := range res {
if len(v.Avatar) <= 0 {
if v.Sex == mysql.MAN {
v.Avatar = common.MakeFullUrl(common.DefaultAvatarMan)
} else if v.Sex == mysql.WOMAN {
v.Avatar = common.MakeFullUrl(common.DefaultAvatarWoman)
}
}
}
}
return res, nil
}
func ToUserTinyBy(user *user_m.User) *user_m.UserTiny {
return &user_m.UserTiny{
ID: user.ID,
Avatar: IfLogoutStr(IfLogout(user.LogoutTime), "", user.Avatar),
ExternalId: user.ExternalId,
Nick: IfLogoutNick(IfLogout(user.LogoutTime), user.Code, user.Nick),
Sex: user.Sex,
Code: user.Code,
Country: user.Country,
CountryIcon: user.CountryIcon,
IsPrettyCode: user.IsPrettyCode(),
IsLogout: IfLogout(user.LogoutTime),
Birthday: BirthdayToUint64(&user.Birthday),
}
}
func IfLogout(logoutTime int64) bool {
return logoutTime > 0 && time.Now().Unix() > logoutTime
}
func BirthdayToUint64(birthday *mysql.Timestamp) *uint64 {
if *birthday == 0 {
return nil
}
return (*uint64)(birthday)
}
func IfLogoutStr(condition bool, trueVal, falseVal string) string {
if condition {
return trueVal
}
return falseVal
}
func IfLogoutNick(condition bool, code string, nick string) string {
if condition {
return "Hilo No." + code
}
return nick
}
package group_ev
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql"
)
var txGroupInListen = new(domain.EventBase)
// 进房事件
type TxGroupInEvent struct {
GroupId string // imGroupId
UserId mysql.ID
ExternalId string
Nick string
Avatar string
IsMember bool //是否永久成员
IsVip bool
NobleLevel uint16
}
func AddTxGroupInEventSync(callback func(model *domain.Model, event interface{}) error) {
domain.AddEventSync(txGroupInListen, callback)
}
func AddTxGroupInEventAsync(callback func(model *domain.Model, event interface{}) error) {
domain.AddEventAsync(txGroupInListen, callback)
}
func PublishTxGroupInEvent(model *domain.Model, event interface{}) error {
return domain.PublishEvent(txGroupInListen, model, event)
}
package group_power_ev
import (
"git.hilo.cn/hilo-common/domain"
)
//注册监听
var groupPowerExpireNoticeListen = new(domain.EventBase)
type GroupPowerExpireNoticeEvent struct {
}
//添加领域事件,在每个领域模型中init中添加,因为这是静态业务,非动态的。
func AddGroupPowerExpireNoticeSync(callback func(model *domain.Model, event interface{}) error) {
domain.AddEventSync(groupPowerExpireNoticeListen, callback)
}
//加入到异步操作中
func AddGroupPowerExpireNoticeAsync(callback func(model *domain.Model, event interface{}) error) {
domain.AddEventAsync(groupPowerExpireNoticeListen, callback)
}
//领域事件发布
func PublishGroupPowerExpireNotice(model *domain.Model, event interface{}) error {
return domain.PublishEvent(groupPowerExpireNoticeListen, model, event)
}
package group_power_ev
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql"
)
//注册监听
var groupPowerUpgradeListen = new(domain.EventBase)
type GroupPowerUpgradeEvent struct {
GroupPowerId mysql.ID
}
//添加领域事件,在每个领域模型中init中添加,因为这是静态业务,非动态的。
func AddGroupPowerUpgradeSync(callback func(model *domain.Model, event interface{}) error) {
domain.AddEventSync(groupPowerUpgradeListen, callback)
}
//加入到异步操作中
func AddGroupPowerUpgradeAsync(callback func(model *domain.Model, event interface{}) error) {
domain.AddEventAsync(groupPowerUpgradeListen, callback)
}
//领域事件发布
func PublishGroupPowerUpgrade(model *domain.Model, event interface{}) error {
return domain.PublishEvent(groupPowerUpgradeListen, model, event)
}
package mic_ev
import (
"git.hilo.cn/hilo-common/domain"
)
var onMicListen = new(domain.EventBase)
// 在麦上事件
type OnMicEvent struct {
GroupUuid string // 群组uuid
I int // 麦位
ExternalId string // 麦中的人
UserId uint64 // 麦中的人
Forbid bool // 静音 true:静音,false:没有静音
Timestamp int64 // 上麦的的时间戳
Ts int64
}
func AddOnMicEventSync(callback func(model *domain.Model, event interface{}) error) {
domain.AddEventSync(onMicListen, callback)
}
func AddOnMicEventAsync(callback func(model *domain.Model, event interface{}) error) {
domain.AddEventAsync(onMicListen, callback)
}
func PublishOnMicEvent(model *domain.Model, event interface{}) error {
return domain.PublishEvent(onMicListen, model, event)
}
package common
import (
"context"
"encoding/json"
"git.hilo.cn/hilo-common/mylogrus"
"git.hilo.cn/hilo-common/resource/mysql"
"git.hilo.cn/hilo-common/resource/redisCli"
"git.hilo.cn/hilo-common/utils"
"hilo-group/_const/redis_key"
"hilo-group/myerr"
"github.com/bluele/gcache"
"time"
)
func GetUserMedalMergeCache(userId mysql.ID) ([]uint32, error) {
bData, err := GetCache(redis_key.GetUserMedalMerge(userId))
if err != nil {
return nil, myerr.WrapErr(err)
}
// 改成lru
var userMedalMergeLru = gcache.New(10000).LRU().Build()
res := make([]uint32, 0)
err = json.Unmarshal(bData, &res)
if err != nil {
return nil, myerr.WrapErr(err)
func GetUserMedalMergeCache(userId mysql.ID) ([]uint32, error) {
if data, err := userMedalMergeLru.Get(userId); err == nil {
return data.([]uint32), nil
}
return res, nil
return nil, nil
}
func SetUserMedalMergeCache(userId mysql.ID, data []uint32) error {
err := SetCache(redis_key.GetUserMedalMerge(userId), data, time.Hour*2)
if err != nil {
mylogrus.MyLog.Errorf("SetUserMedalMerge err:%s", err)
return myerr.WrapErr(err)
}
return nil
func SetUserMedalMergeCache(userId mysql.ID, data []uint32) {
_ = userMedalMergeLru.SetWithExpire(userId, data, time.Minute*15)
}
// 删除勋章缓存, 延迟删除
......@@ -44,41 +30,6 @@ func DelUserMedalMergeCacheDelay(userId mysql.ID) {
}()
}
func DelUserMedalMergeCache(userId mysql.ID) error {
err := DelCache(redis_key.GetUserMedalMerge(userId))
if err != nil {
mylogrus.MyLog.Errorf("DetUserMedalMerge err:%s, userId:%v", err, userId)
return myerr.WrapErr(err)
}
return nil
}
func DelCache(key string) error {
err := redisCli.GetRedis().Del(context.Background(), key).Err()
if err != nil {
mylogrus.MyLog.Errorf("DelCache key:%s, err:%s", key, err)
return err
}
return nil
}
func GetCache(key string) ([]byte, error) {
data, err := redisCli.GetRedis().Get(context.Background(), key).Bytes()
if err != nil {
return nil, err
}
return data, nil
}
func SetCache(key string, data interface{}, expire time.Duration) error {
jData, err := json.Marshal(data)
if err != nil {
return err
}
err = redisCli.GetRedis().Set(context.Background(), key, jData, expire).Err()
if err != nil {
mylogrus.MyLog.Errorf("SetCache key:%s, data:%v, err:%s", key, data, err)
return err
}
return nil
func DelUserMedalMergeCache(userId mysql.ID) {
userMedalMergeLru.Remove(userId)
}
package diamond_m
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/mylogrus"
"git.hilo.cn/hilo-common/resource/mysql"
"gorm.io/gorm"
"hilo-group/common"
"hilo-group/myerr"
)
type DiamondDealer struct {
mysql.Entity
UserId uint64
Diamond uint32
Wechat string
Whatsapp string
Contact string
Status int
HasInvite int
IsFamilyAgent int8
}
func (dealer *DiamondDealer) Save(db *gorm.DB) error {
if dealer.ID > 0 {
db = db.Omit("diamond", "status")
} else {
dealer.Status = common.SWITCH_ON
}
return db.Save(dealer).Error
}
func (dealer *DiamondDealer) Get(db *gorm.DB) error {
return db.Where(dealer).First(dealer).Error
}
func IsDiamondDealer(db *gorm.DB, userId uint64) (bool, error) {
dd := DiamondDealer{UserId: userId, Status: common.SWITCH_ON}
if err := dd.Get(db); err != nil {
if err == gorm.ErrRecordNotFound {
return false, nil
} else {
return false, err
}
}
return true, nil
}
// 是否是家族代理
func IsFamilyDiamondDealer(db *gorm.DB, userId uint64) (bool, error) {
dd := DiamondDealer{UserId: userId, Status: common.SWITCH_ON, IsFamilyAgent: 1}
if err := dd.Get(db); err != nil {
if err == gorm.ErrRecordNotFound {
return false, nil
} else {
return false, err
}
}
return true, nil
}
func GetDiamondDealer(db *gorm.DB, userId uint64) (*DiamondDealer, error) {
dd := &DiamondDealer{UserId: userId, Status: common.SWITCH_ON}
if err := dd.Get(db); err != nil {
if err == gorm.ErrRecordNotFound {
return nil, nil
} else {
return nil, myerr.WrapErr(err)
}
}
return dd, nil
}
func (dealer *DiamondDealer) GetAll(db *gorm.DB, status *uint8) ([]DiamondDealer, error) {
rows := make([]DiamondDealer, 0)
if status == nil {
if err := db.Where(dealer).Find(&rows).Error; err != nil {
return nil, err
}
} else if err := db.Where(dealer).Where("status = ?", *status).Find(&rows).Error; err != nil {
return nil, err
}
return rows, nil
}
func (dealer *DiamondDealer) Remove(db *gorm.DB) (int64, error) {
result := db.Where(dealer).Delete(&DiamondDealer{})
return result.RowsAffected, result.Error
}
func (dealer *DiamondDealer) SafeReduceDiamond(db *gorm.DB, diamond uint32) (int64, error) {
result := db.Model(&DiamondDealer{}).Where(dealer).Where("diamond >= ?", diamond).UpdateColumn("diamond", gorm.Expr("diamond - ?", diamond))
return result.RowsAffected, result.Error
}
func (dealer *DiamondDealer) AddDiamond(db *gorm.DB, diamond uint32) (int64, error) {
result := db.Model(&DiamondDealer{}).Where(dealer).Where("status = ?", common.SWITCH_ON).UpdateColumn("diamond", gorm.Expr("diamond + ?", diamond))
return result.RowsAffected, result.Error
}
func (dealer *DiamondDealer) SetStatus(db *gorm.DB, status uint8) error {
return db.Model(&DiamondDealer{}).Where(dealer).Update("status", status).Error
}
type DealerTransferDetail struct {
mysql.Entity
DealerId uint64
ReceiverId uint64
Diamond uint32
Dollar uint
}
func (dtd *DealerTransferDetail) Create(db *gorm.DB) error {
return db.Create(dtd).Error
}
func (dfd *DealerTransferDetail) Find(db *gorm.DB, offset, limit int) ([]DealerTransferDetail, error) {
rows := make([]DealerTransferDetail, 0)
if err := db.Where(dfd).Order("created_time DESC").Offset(offset).Limit(limit).Find(&rows).Error; err != nil {
return nil, err
}
return rows, nil
}
func (dfd *DealerTransferDetail) CountByDealer(db *gorm.DB, dealerIds []uint64) (map[uint64]uint, error) {
type summary struct {
DealerId uint64
C uint
}
rows := make([]summary, 0)
if err := db.Model(&DealerTransferDetail{}).Where("dealer_id IN ?", dealerIds).
Select("dealer_id, COUNT(0) AS c").Group("dealer_id").Find(&rows).Error; err != nil {
return nil, err
}
result := make(map[uint64]uint, 0)
for _, i := range rows {
result[i.DealerId] = i.C
}
return result, nil
}
func (dfd *DealerTransferDetail) Sum(db *gorm.DB) (uint, uint32, uint, error) {
type summary struct {
C uint
Diamond uint32
Dollar uint
}
s := summary{}
if err := db.Model(&DealerTransferDetail{}).Where(dfd).
Select("COUNT(0) AS c, SUM(diamond) AS diamond, SUM(dollar) AS dollar").First(&s).Error; err != nil {
return 0, 0, 0, err
}
return s.C, s.Diamond, s.Dollar, nil
}
type DealerChargeDetail struct {
mysql.Entity
DealerId uint64
MgrId uint64
Diamond uint32
Dollar uint
PaymentMethod string
Type uint8
Money float32 `json:"money"` // 支付的货币数值
Currency string `json:"currency"` // 支付货币
GoodsId string `json:"goodsId"` // 充值钻石套餐id/商品id
}
func (dcd *DealerChargeDetail) Create(db *gorm.DB) error {
return db.Create(dcd).Error
}
type DealerCountry struct {
DealerId uint64
Country string
}
func (dc *DealerCountry) Find(db *gorm.DB) ([]DealerCountry, error) {
rows := make([]DealerCountry, 0)
if err := db.Where(dc).Find(&rows).Error; err != nil {
return nil, err
}
return rows, nil
}
func (dc *DealerCountry) Delete(db *gorm.DB) error {
return db.Where(dc).Delete(&DealerCountry{}).Error
}
func (dc *DealerCountry) BatchInsert(db *gorm.DB, dealerId uint64, countries []string) error {
rows := make([]DealerCountry, 0)
for _, i := range countries {
rows = append(rows, DealerCountry{
DealerId: dealerId,
Country: i,
})
}
return db.Create(&rows).Error
}
// 活动排行榜黑名单 获取所有已经上架代理币商的群组id
func GetAllValidActivityBlackImGroupIds(model *domain.Model) []mysql.Str {
//return []mysql.Str{"HTGS#a88745892", "@TGS#3UW6RFSIX"}
var imGroupIds []mysql.Str
subQuery := model.Db.WithContext(model).Model(DiamondDealer{}).Where("status = 1").Select("user_id")
if err := model.Db.WithContext(model).Table("group_info").Select("im_group_id").Where("owner in (?)", subQuery).Scan(&imGroupIds).Error; err != nil {
mylogrus.MyLog.Errorf("GetAllValidActivityBlackImGroupIds fail:%v", err)
}
imGroupIds = append(imGroupIds, "HTGS#a88745892", "@TGS#3UW6RFSIX")
return imGroupIds
}
package diamond_m
import (
"fmt"
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/mylogrus"
"git.hilo.cn/hilo-common/resource/mysql"
"git.hilo.cn/hilo-common/utils"
"gorm.io/gorm"
"hilo-group/_const/enum/diamond_e"
"hilo-group/domain/model"
"hilo-group/myerr"
"hilo-group/myerr/bizerr"
"strconv"
......@@ -40,6 +40,11 @@ type DiamondAccountDetail struct {
diamondAccount *DiamondAccount `gorm:"-"`
}
func (DiamondAccountDetail) TableName() string {
month := time.Now().Format("200601")
return fmt.Sprintf("diamond_account_detail_%s", month)
}
// 粉钻详情
type DiamondPinkAccountDetail struct {
mysql.Entity
......@@ -110,7 +115,7 @@ func (diamondAccount *DiamondAccount) addDiamondAccountDetail(operateType diamon
var count int64
if diamondOperateSet.FrequencyDay == -1 {
if diamondOperateSet.FrequencyNum != -1 {
diamondAccount.Db.Model(&DiamondAccountDetail{}).Where(&DiamondAccountDetail{
diamondAccount.DB().Table(DiamondAccountDetail{}.TableName()).Where(&DiamondAccountDetail{
UserId: diamondAccount.UserId,
OperateType: operateType,
}).Count(&count)
......@@ -125,7 +130,7 @@ func (diamondAccount *DiamondAccount) addDiamondAccountDetail(operateType diamon
return nil, myerr.WrapErr(err)
}
//一天的次数
diamondAccount.Db.Model(&DiamondAccountDetail{}).Where(&DiamondAccountDetail{
diamondAccount.DB().Table(DiamondAccountDetail{}.TableName()).Where(&DiamondAccountDetail{
UserId: diamondAccount.UserId,
OperateType: operateType,
}).Where("created_time >= ? ", beginTime).Count(&count)
......@@ -133,7 +138,7 @@ func (diamondAccount *DiamondAccount) addDiamondAccountDetail(operateType diamon
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) + " )")
diamondAccount.SetCheckUpdateCondition(" EXISTS (SELECT * from (SELECT COUNT(1) as n from " + DiamondAccountDetail{}.TableName() + " 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,代表值无效,由参数给与
......@@ -197,7 +202,10 @@ func (diamondAccountDetail *DiamondAccountDetail) PersistentNoInTransactional()
}
//持久化diamondAccountDetail
if err := model.Persistent(diamondAccountDetail.Db, diamondAccountDetail); err != nil {
//if err := model.Persistent(diamondAccountDetail.Db, diamondAccountDetail); err != nil {
// return myerr.WrapErr(err)
//}
if err := diamondAccountDetail.DB().Table(diamondAccountDetail.TableName()).Save(diamondAccountDetail).Error; err != nil {
return myerr.WrapErr(err)
}
//改变diamondAccount值
......@@ -245,7 +253,10 @@ func (diamondAccountDetail *DiamondAccountDetail) Persistent() error {
}
//持久化diamondAccountDetail
if err := model.Persistent(diamondAccountDetail.Db, diamondAccountDetail); err != nil {
//if err := model.Persistent(diamondAccountDetail.Db, diamondAccountDetail); err != nil {
// return myerr.WrapErr(err)
//}
if err := diamondAccountDetail.DB().Table(diamondAccountDetail.TableName()).Save(diamondAccountDetail).Error; err != nil {
return myerr.WrapErr(err)
}
//改变diamondAccount值
......
package event_m
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql"
"gorm.io/gorm"
)
// 进房事件消息
type EventGroupIn struct {
mysql.Entity
*domain.Model `gorm:"-"`
Proto mysql.Type
Payload []byte
Mark mysql.YesNo
MarkHiloGroup mysql.YesNo
}
func (EventGroupIn) TableName() string {
return "event_group_in"
}
// 偏移值
type EventGroupInOffsetHiloGroup struct {
mysql.Entity
*domain.Model `gorm:"-"`
MarkOffset mysql.ID
}
// 获取当前偏移值
func GroupOffset(model *domain.Model) (*EventGroupInOffsetHiloGroup, error) {
offset := new(EventGroupInOffsetHiloGroup)
if err := model.Db.WithContext(model).First(offset).Error; err != nil {
if err != gorm.ErrRecordNotFound {
model.Log.Errorf("Offset fail:%v", err)
return nil, err
}
// gorm.ErrRecordNotFound
}
offset.Model = model
return offset, nil
}
// 批量获取进房事件
func FetchEventGroupIn(model *domain.Model, limit int) ([]*EventGroupIn, *EventGroupInOffsetHiloGroup, error) {
offset, err := GroupOffset(model)
if err != nil {
return nil, nil, err
}
var events []*EventGroupIn
if err := model.Db.WithContext(model).Model(EventGroupIn{}).
Where("id > ?", offset.MarkOffset).
Order("id asc").Limit(limit).Find(&events).Error; err != nil {
model.Log.Errorf("FetchEventGroupIn fail:%v", err)
return nil, nil, err
}
return events, offset, nil
}
// 标记已完成
func (p *EventGroupIn) MarkDone() error {
p.MarkHiloGroup = mysql.YES
return p.Db.WithContext(p.Model).Model(EventGroupIn{}).Where("id = ?", p.ID).Update("mark_hilo_group", p.MarkHiloGroup).Limit(1).Error
}
......@@ -9,3 +9,7 @@ func (p *EventGiftSendOffsetHiloGroup) Persistence() error {
func (p *EventGiftSend) Persistence() error {
return model.Persistent(p.Db, p)
}
func (p *EventGroupInOffsetHiloGroup) Persistence() error {
return model.Persistent(p.Db, p)
}
\ No newline at end of file
......@@ -16,10 +16,11 @@ type EventGiftSend struct {
Payload []byte
Mark mysql.YesNo
MarkHiloGroup mysql.YesNo
MarkHiloUser mysql.YesNo
}
func (EventGiftSend) TableName() string {
return "event_gift_send2"
return "event_gift_send"
}
// 偏移值
......
......@@ -29,8 +29,9 @@ type GameInfo struct {
}
type GameConfig struct {
Ludo *GameConfigDiamond `json:"ludo"`
Uno *GameConfigDiamond `json:"uno"`
Ludo *GameConfigDiamond `json:"ludo"`
Uno *GameConfigDiamond `json:"uno"`
Domino *GameConfigDiamond `json:"domino"`
}
type GameConfigDiamond struct {
......
......@@ -127,6 +127,40 @@ func (g *GiftOperate) GetConsumeByRange(beginTime, endTime time.Time) (uint32, u
if len(rows) <= 0 {
return 0, 0, nil
}
//if beginTime.Unix() >= 1691337600 && beginTime.Unix() < 1691942400 { // 因为这周水果机被部分人刷币,所以这里做了特殊的处理
// reduceMap := map[string]uint64{
// "HTGS#a63226380": 20000000,
// //"HTGS#a42641278": 10000000,
// "@TGS#3ZZ5GZLHA": 27141539,
// "HTGS#a81630128": 8955410,
// "HTGS#a42300598": 50211301,
// "HTGS#a40088696": 10000000,
// "HTGS#a21700997": 14352310,
// "HTGS#a83608384": 49644203,
// "@TGS#33GDXTSIH": 50000000,
// "HTGS#a50538513": 15000000,
// "HTGS#a77282385": 15000000,
// "HTGS#a59437326": 10000000,
// "HTGS#a16909405": 10000000,
// "HTGS#a44104431": 16861206,
// "HTGS#a56794634": 59591313,
// "HTGS#a11286025": 31232311,
// "HTGS#a17238550": 52309338,
// "HTGS#a83592361": 79545067,
// "HTGS#a39882521": 10255093,
// }
// if reduceNum, ok := reduceMap[g.SceneUid]; ok {
// if g.Log != nil {
// g.Log.Infof("fruit diamond reduceMap,groupId:%v,reduceNum:%v", g.SceneUid, reduceNum)
// }
// if rows[0].Consume >= reduceNum {
// rows[0].Consume -= reduceNum
// } else {
// rows[0].Consume = 0
// }
// }
//}
return rows[0].C, rows[0].Consume, nil
}
......@@ -148,6 +182,17 @@ func (g *GiftOperate) BatchGetConsumeByRange(beginTime, endTime time.Time) ([]Sc
return rows, nil
}
func (g *GiftOperate) BatchGetSupportList(model *domain.Model, beginTime, endTime time.Time) ([]uint64, error) {
userIds := make([]uint64, 0)
err := model.DB().Model(g).
Select("DISTINCT(send_user_id) AS user_id").
Where(g).Where("created_time BETWEEN ? AND ?", beginTime, endTime).Pluck("user_id", &userIds).Error
if err != nil {
return nil, err
}
return userIds, nil
}
func SumSendGift(model *domain.Model, sendUserId mysql.ID, giftId mysql.ID) (uint32, error) {
type Result struct {
N uint32
......
package groupPower_m
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql"
"gorm.io/gorm"
"hilo-group/_const/enum/groupPower_e"
"hilo-group/common"
"hilo-group/common/utime"
"hilo-group/myerr"
"hilo-group/myerr/bizerr"
"time"
)
//type GroupPowerGrade struct {
// GroupPowerId uint64 `json:"group_power_id"`
// Exp int64 `json:"exp"`
// Grade int32 `json:"grade"`
// ExpireAt time.Time `json:"expire_at"`
//}
type GroupPowerQuitLog struct {
Id uint64 `json:"id"`
UserId uint64 `json:"user_id"`
MgrId uint64 `json:"mgr_id"`
CreatedTime time.Time `json:"created_time"`
GroupPowerId uint64 `json:"group_power_id"`
}
func (this *GroupPower) Get(model *domain.Model) (*GroupPower, error) {
group := new(GroupPower)
err := model.Db.Where(this).First(&group).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return nil, nil
}
return nil, err
}
grade := new(GroupPowerGrade)
err = model.Db.Model(&GroupPowerGrade{}).Where("group_power_id=? and expire_at > ?", this.ID, time.Now().Format(utime.Layout)).First(&grade).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
if grade.GroupPowerId > 0 {
group.Grade = grade.Grade
}
return group, nil
}
func (gpu *GroupPowerUser) GetBy(model *domain.Model, pageSize, pageIndex int) ([]*GroupPowerUser, int64, int, bool, error) {
rows := make([]*GroupPowerUser, 0)
db := model.Db.Model(GroupPowerUser{}).Where(gpu).Order("field(`role`, 2, 3, 1),`id`")
var count int64
err := db.Count(&count).Error
if err != nil {
return nil, 0, 0, false, err
}
err = db.Limit(pageSize).Offset(pageIndex).Find(&rows).Error
if err != nil {
return nil, 0, 0, false, err
}
nextPageIndex, hasNextPage := common.PageNext(count, pageIndex, pageSize)
return rows, count, nextPageIndex, hasNextPage, nil
}
func (gpu *GroupPowerUser) GetGroupPowerUser(model *domain.Model) (*GroupPowerUser, error) {
rows := make([]*GroupPowerUser, 0)
err := model.Db.Where(gpu).Find(&rows).Error
if err != nil {
return nil, err
}
if len(rows) == 0 {
return nil, nil
}
return rows[0], nil
}
func (gpu *GroupPowerUser) Create(db *gorm.DB) error {
return db.Create(gpu).Error
}
func QuitFamily(model *domain.Model, userId, mgrId, familyId uint64) error {
err := model.Db.Exec("delete from group_power_user where group_power_id = ? and user_id = ?", familyId, userId).Error
if err != nil {
return err
}
// log
log := &GroupPowerQuitLog{UserId: userId, MgrId: mgrId, GroupPowerId: familyId, CreatedTime: time.Now()}
return model.Db.Create(log).Error
}
func GroupPowerQuitList(model *domain.Model, familyId uint64, pageSize, pageIndex int) ([]*GroupPowerQuitLog, int, bool, error) {
rows := make([]*GroupPowerQuitLog, 0)
db := model.Db.Model(GroupPowerQuitLog{}).Where("group_power_id = ?", familyId).Order("created_time desc")
var count int64
err := db.Count(&count).Error
if err != nil {
return nil, 0, false, err
}
err = db.Limit(pageSize).Offset(pageIndex).Find(&rows).Error
if err != nil {
return nil, 0, false, err
}
nextIdx, hasNext := common.PageNext(count, pageIndex, pageSize)
return rows, nextIdx, hasNext, nil
}
func UpdateFamilyAdmin(model *domain.Model, userId, familyId uint64, role groupPower_e.GroupPowerUserRole) error {
err := model.Db.Exec("update group_power_user set role = ? where group_power_id = ? and user_id = ?", role, familyId, userId).Error
if err != nil {
return err
}
return nil
}
func UpdateFamily(model *domain.Model, familyId uint64, name, nameplate, declaration, icon string) error {
if familyId == 0 || (name == "" && nameplate == "" && declaration == "" && icon == "") {
return nil
}
var groupPower GroupPower
if err := model.DB().Model(GroupPower{}).Where("id = ?", familyId).First(&groupPower).Error; err != nil {
return err
}
// 修改铭牌
if nameplate != "" {
sql := "UPDATE `group_power` a left join (SELECT ? `id` FROM group_power WHERE nameplate = ?) b on a.id = b.id SET a.`nameplate`=?,modify_nameplate = 1 where a.id=? and b.id is null;"
result := model.Db.Exec(sql, familyId, nameplate, nameplate, familyId)
if result.Error != nil {
return myerr.WrapErr(result.Error)
}
if result.RowsAffected <= 0 {
return myerr.WrapErr(bizerr.GroupPowerHaveChangeInfo)
}
return nil
}
db := model.Db.Model(GroupPower{})
updateMap := make(map[string]interface{})
if name != "" {
updateMap["name"] = name
if groupPower.ModifyNameplate != mysql.YES {
// 同步修改铭牌
n := len([]rune(name))
if n > groupPower_e.LongestNameplate {
n = groupPower_e.LongestNameplate
}
updateMap["nameplate"] = string([]rune(name[0:n]))
}
}
if declaration != "" {
updateMap["declaration"] = declaration
}
if icon != "" {
updateMap["icon"] = icon
}
result := db.Where("group_power.id = ?", familyId).Updates(updateMap).Limit(1)
if result.Error != nil {
return myerr.WrapErr(result.Error)
}
if result.RowsAffected <= 0 {
return myerr.WrapErr(bizerr.GroupPowerHaveChangeInfo)
}
return nil
}
func IsExistsNameplate(model *domain.Model, nameplate string) bool {
var count int64
err := model.Db.Model(GroupPower{}).Where("nameplate = ?", nameplate).Count(&count).Error
if err != nil {
model.Log.Errorf("IsExistsNameplate err:%v, nameplate:%s", err, nameplate)
return false
}
if count > 0 {
return true
}
return false
}
func GetMemberNum(model *domain.Model, familyId uint64) (int64, error) {
var count int64
err := model.Db.Model(GroupPowerUser{}).Where("group_power_id=?", familyId).Count(&count).Error
if err != nil {
return 0, err
}
return count, nil
}
......@@ -22,10 +22,17 @@ import (
type GroupPower struct {
mysql.Entity
*domain.Model `gorm:"-"`
GroupUid mysql.Str
Name mysql.Str
Status groupPower_e.GroupPowerStatus
*domain.Model `gorm:"-"`
GroupUid mysql.Str
Name mysql.Str
Status groupPower_e.GroupPowerStatus
Nameplate mysql.Str // 铭牌
Declaration mysql.Str // 宣言
Icon mysql.Str // 头像
GradeName mysql.Str // 等级称号
GradeMedal mysql.Str // 等级勋章图片
Grade groupPower_e.GroupPowerGrade `gorm:"-"`
ModifyNameplate mysql.YesNo
}
type GroupPowerUser struct {
......@@ -36,6 +43,17 @@ type GroupPowerUser struct {
Role groupPower_e.GroupPowerUserRole
}
type ActFamilyMonthRankLog struct {
Id uint64 `json:"id"`
Period string `json:"period"`
FamilyId uint64 `json:"family_id"`
RankFamily int `json:"rank_family"`
RankUser int `json:"rank_user"`
UserId uint64 `json:"user_id"`
Award string `json:"award"`
Area int `json:"area"`
}
func (gpu *GroupPowerUser) Get(db *gorm.DB) ([]GroupPowerUser, error) {
rows := make([]GroupPowerUser, 0)
err := db.Where(gpu).Find(&rows).Error
......@@ -57,6 +75,22 @@ func GetPowerOwner(db *gorm.DB, powerId uint64) (uint64, error) {
return records[0].UserId, nil
}
func GetPowerOwnerMap(model *domain.Model, powerIds []uint64) (map[uint64]uint64, error) {
rows := make([]GroupPowerUser, 0)
if len(powerIds) > 0 {
if err := model.DB().Model(&GroupPowerUser{}).
Where("group_power_id IN ? and role = ?", powerIds, groupPower_e.GroupPowerUserRoleMgr).
Find(&rows).Error; err != nil {
return nil, err
}
}
result := make(map[uint64]uint64, 0)
for _, i := range rows {
result[i.GroupPowerId] = i.UserId
}
return result, nil
}
func GetMyPowerId(db *gorm.DB, userId uint64) (uint64, error) {
gpu := GroupPowerUser{UserId: userId, Role: groupPower_e.GroupPowerUserRoleMgr}
records, err := gpu.Get(db)
......@@ -334,6 +368,34 @@ func GetGroupPowerByGroupOrNil(model *domain.Model, groupUid string) (*GroupPowe
return &groupPower, nil
}
// 某个势力的势力主是否是代理
func IsGroupPowerHasMgrDealer(model *domain.Model, groupId mysql.ID) (bool, error) {
var num int64
if err := model.Db.Raw("select count(1) from (select * from diamond_dealer where user_id in "+
"(select user_id from group_power_user where group_power_id = ? and role = ?)) a", groupId, groupPower_e.GroupPowerUserRoleMgr).
Scan(&num).Error; err != nil {
return false, myerr.WrapErr(err)
}
if num > 0 {
return true, nil
}
return false, nil
}
// 某个家族是否有家族代理
func IsGroupPowerHasFamilyAgent(model *domain.Model, groupId mysql.ID) (bool, error) {
var num int64
if err := model.Db.Raw("select count(1) from diamond_dealer where status=1 and is_family_agent=1 and user_id in "+
"(select user_id from group_power_user where group_power_id = ?)", groupId).
Scan(&num).Error; err != nil {
return false, myerr.WrapErr(err)
}
if num > 0 {
return true, nil
}
return false, nil
}
func GetGroupPowerMap(db *gorm.DB, userIds []mysql.ID) (map[mysql.ID]uint64, error) {
rows := make([]GroupPowerUser, 0)
if len(userIds) > 0 {
......@@ -348,47 +410,28 @@ func GetGroupPowerMap(db *gorm.DB, userIds []mysql.ID) (map[mysql.ID]uint64, err
return result, nil
}
func GetGroupPowerNames(db *gorm.DB, ids []mysql.ID) (map[mysql.ID]string, error) {
// return
func GetGroupPowerNames(db *gorm.DB, ids []mysql.ID) (map[mysql.ID]string, map[mysql.ID]string, error) {
type record struct {
Id mysql.ID
Name string
Id mysql.ID
Name string
Nameplate string
}
rows := make([]record, 0)
result := make(map[mysql.ID]string, 0)
result2 := make(map[mysql.ID]string, 0)
if len(ids) > 0 {
if err := db.Model(&GroupPower{}).Select("p.id, i.name").
if err := db.Model(&GroupPower{}).Select("p.id, i.name,p.nameplate").
Joins("AS p INNER JOIN group_info AS i ON p.group_uid = i.im_group_id").
Where("p.id IN ?", ids).Find(&rows).Error; err != nil {
return nil, err
return result, result2, err
}
}
result := make(map[mysql.ID]string, 0)
for _, i := range rows {
result[i.Id] = i.Name
result2[i.Id] = i.Nameplate
}
return result, nil
}
type GroupPowerInfo struct {
PowerId mysql.ID
Owner mysql.ID
Name string
}
func BatchGetGroupPower(db *gorm.DB, ids []mysql.ID) (map[mysql.ID]GroupPowerInfo, error) {
rows := make([]GroupPowerInfo, 0)
if len(ids) > 0 {
if err := db.Model(&GroupPower{}).Select("p.id AS power_id, u.user_id AS owner, p.name").
Joins("AS p INNER JOIN group_power_user AS u ON p.id = u.group_power_id").
Where("p.id IN ? AND p.status = ? AND role = ?", ids, groupPower_e.GroupPowerUserHas, groupPower_e.GroupPowerUserRoleMgr).
Find(&rows).Error; err != nil {
return nil, err
}
}
result := make(map[mysql.ID]GroupPowerInfo, 0)
for _, i := range rows {
result[i.PowerId] = i
}
return result, nil
return result, result2, nil
}
func GetGroupPower(model *domain.Model, id mysql.ID) (*GroupPower, error) {
......@@ -455,6 +498,16 @@ func GetGroupPowerMgr(model *domain.Model, groupPowerId mysql.ID) (mysql.ID, err
return groupPowerUser.UserId, nil
}
//获取势力主和管理员
func GetGroupPowerMgrList(model *domain.Model, groupPowerId mysql.ID) ([]mysql.ID, error) {
res := make([]mysql.ID, 0)
err := model.Db.Model(GroupPowerUser{}).Select("user_id").Where("group_power_id = ? and role in (2,3)", groupPowerId).Scan(&res).Error
if err != nil {
return res, myerr.WrapErr(err)
}
return res, nil
}
//运营平台让用户离开
func (groupPower *GroupPower) MgrUserLeave(userId mysql.ID) (*GroupPowerUser, error) {
//
......@@ -648,3 +701,40 @@ func GetUserGroupPower(model *domain.Model, userId uint64) (uint64, string, erro
}
return gpu.GroupPowerId, powerName, nil
}
// 获取势力下的所有群组
func GetGroupPowerGroups(model *domain.Model, groupPowerId mysql.ID) ([]*group_m.GroupInfo, error) {
var res []*group_m.GroupInfo
var ownerIds []mysql.ID
if err := model.DB().Model(GroupPowerUser{}).Select("user_id").Where("group_power_id = ?", groupPowerId).Scan(&ownerIds).Error; err != nil {
model.Log.Errorf("GetGroupPowerGroups fail:%v", err)
return nil, err
}
if len(ownerIds) <= 0 {
return res, nil
}
if err := model.DB().Model(group_m.GroupInfo{}).Where("owner in ?", ownerIds).Find(&res).Error; err != nil {
model.Log.Errorf("GetGroupPowerGroups fail:%v", err)
return nil, err
}
return res, nil
}
// 批量获取势力用户
// return userId->GroupPowerUser
func BatchGetGroupPowerUser(model *domain.Model, userIds []mysql.ID) (map[mysql.ID]GroupPowerUser, error) {
var rows []GroupPowerUser
res := make(map[mysql.ID]GroupPowerUser)
if err := model.Db.Model(GroupPowerUser{}).Where("user_id in ?", userIds).Find(&rows).Error; err != nil {
model.Log.Errorf("BatchGetGroupPowerUser fail:%v", err)
return res, err
}
for i, v := range rows {
res[v.UserId] = rows[i]
}
return res, nil
}
func CreateActFamilyMonthRankLog(model *domain.Model, list []*ActFamilyMonthRankLog) error {
return model.DB().CreateInBatches(&list, 50).Error
}
package groupPower_m
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql"
"git.hilo.cn/hilo-common/utils"
"github.com/jinzhu/now"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"hilo-group/_const/enum/groupPower_e"
"hilo-group/_const/redis_key/mic_k"
"hilo-group/domain/event/group_power_ev"
"time"
)
type GroupPowerDayExp struct {
Date string
GroupPowerId mysql.ID
Exp mysql.Num
CreatedTime time.Time `gorm:"->"`
UpdatedTime time.Time `gorm:"->"`
}
type GroupPowerGrade struct {
GroupPowerId mysql.ID
Exp mysql.Num
Grade groupPower_e.GroupPowerGrade
ExpireAt time.Time
CreatedTime time.Time `gorm:"->"`
UpdatedTime time.Time `gorm:"->"`
}
type GroupPowerExpDetail struct {
mysql.Entity
GroupPowerId mysql.ID
UserId mysql.ID
Exp mysql.Num
AddReduce mysql.AddReduce
BefNum mysql.Num
AftNum mysql.Num
Remark string
}
// 增加家族经验
// 达到经验值之后升级
// 单进程同步执行,不考虑并发
func IncrGroupPowerExp(txModel *domain.Model, groupPowerId mysql.ID, exp mysql.Num, userId mysql.ID, remark string) error {
var err error
defer func() {
if err != nil {
txModel.Log.Errorf("IncrGroupPowerExp fail,id:%v,exp:%v,err:%v", groupPowerId, exp, err)
}
}()
// 增加家族经验-天
date := time.Now().Format("2006-01-02")
gpe := &GroupPowerDayExp{
Date: date,
GroupPowerId: groupPowerId,
Exp: exp,
}
if err = txModel.DB().Model(GroupPowerDayExp{}).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "date"}, {Name: "group_power_id"}},
DoUpdates: clause.Assignments(map[string]interface{}{
"exp": gorm.Expr("exp + ?", gpe.Exp)})}).Create(gpe).Error; err != nil {
return err
}
// 增加家族经验-总
gpg := new(GroupPowerGrade)
// insert
if err := txModel.DB().Model(GroupPowerGrade{}).Where("group_power_id = ?", groupPowerId).First(gpg).Error; err != nil {
if err != gorm.ErrRecordNotFound {
return err
}
// gorm.ErrRecordNotFound
gpg = &GroupPowerGrade{
GroupPowerId: groupPowerId,
Exp: exp,
Grade: 0,
ExpireAt: time.Time{},
}
if err = txModel.DB().Create(gpg).Error; err != nil {
return err
}
} else {
// or update
if err := txModel.DB().Model(GroupPowerGrade{}).Where("group_power_id = ?", groupPowerId).
UpdateColumn("exp", gorm.Expr("exp + ?", exp)).Error; err != nil {
return err
}
}
//if err = txModel.DB().Model(GroupPowerGrade{}).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "group_power_id"}},
// DoUpdates: clause.Assignments(map[string]interface{}{
// "exp": gorm.Expr("exp + ?", gpg.Exp)})}).Create(gpg).Error; err != nil {
// return err
//}
// 当前写后读
latestGrade := new(GroupPowerGrade)
if err = txModel.DB().Model(GroupPowerGrade{}).Where("group_power_id = ?", groupPowerId).First(latestGrade).Error; err != nil {
return err
}
// 记录明细
detail := &GroupPowerExpDetail{
GroupPowerId: groupPowerId,
UserId: userId,
Exp: exp,
AddReduce: mysql.ADD,
BefNum: latestGrade.Exp - exp,
AftNum: latestGrade.Exp,
Remark: remark,
}
if err = txModel.DB().Model(GroupPowerExpDetail{}).Create(detail).Error; err != nil {
return err
}
// 达到经验值之后升级
for grade := groupPower_e.GroupPowerGradeMax; grade >= groupPower_e.GroupPowerGrade0; grade-- {
if latestGrade.Exp > groupPower_e.GroupPowerGradeExp[grade] {
if latestGrade.Grade < grade { // 升级
expireAt := now.EndOfMonth()
expireAt = utils.AddDate(expireAt, 0, 1) // 等级有效期到下个月月底
updateAttrs := map[string]interface{}{
"grade": grade,
"expire_at": expireAt,
}
if err = txModel.DB().Model(GroupPowerGrade{}).Where("group_power_id = ?", latestGrade.GroupPowerId).UpdateColumns(updateAttrs).Error; err != nil {
return err
}
// 升级发事件
_ = group_power_ev.PublishGroupPowerUpgrade(txModel, &group_power_ev.GroupPowerUpgradeEvent{
GroupPowerId: groupPowerId,
})
}
break
}
}
return nil
}
// 增加势力上麦经验
// 事务操作
func IncrGroupPowerExpOnMic(model *domain.Model, groupPowerId, userId mysql.ID) error {
key := mic_k.GetMicGroupPowerOnMic(userId)
minutes, err := model.Redis.IncrBy(model, key, 1).Result()
if err != nil {
model.Log.Errorf("IncrGroupPowerExpOnMic fail:%v", err)
return err
}
model.Redis.Expire(model, key, time.Hour*24) // ttl 一天
// 每日最多1800经验 = 18个10分钟 = 180分钟
if minutes > 180 {
return nil
}
if minutes%10 == 0 {
return IncrGroupPowerExp(model, groupPowerId, 100, userId, "上麦10分钟")
}
return nil
}
// 清理所有家族的经验
func ClearGroupPowerExp(model *domain.Model) error {
var groupPowerGrades []*GroupPowerGrade
if err := model.DB().Model(GroupPowerGrade{}).Where("exp > 0").Find(&groupPowerGrades).Error; err != nil {
return err
}
return model.Transaction(func(model *domain.Model) error {
for _, grade := range groupPowerGrades {
if err := model.DB().Model(GroupPowerGrade{}).Where("group_power_id = ?", grade.GroupPowerId).UpdateColumn("exp", 0).Error; err != nil {
return err
}
// 记录明细
detail := &GroupPowerExpDetail{
GroupPowerId: grade.GroupPowerId,
UserId: 0,
Exp: 0,
AddReduce: mysql.SET,
BefNum: grade.Exp,
AftNum: 0,
Remark: "每月清零",
}
if err := model.DB().Model(GroupPowerExpDetail{}).Create(detail).Error; err != nil {
return err
}
}
return nil
})
}
// 清理过期家族等级
func ClearGroupPowerGrade(model *domain.Model) error {
var groupPowerGrades []*GroupPowerGrade
if err := model.DB().Model(GroupPowerGrade{}).Where("expire_at < ?", time.Now()).Find(&groupPowerGrades).Error; err != nil {
return err
}
return model.Transaction(func(model *domain.Model) error {
for _, grade := range groupPowerGrades {
updateAttrs := map[string]interface{}{
"grade": 0,
"expire_at": time.Time{},
}
if err := model.DB().Model(GroupPowerGrade{}).Where("group_power_id = ?", grade.GroupPowerId).Updates(updateAttrs).Error; err != nil {
return err
}
}
return nil
})
}
// 批量获取家族等级
func MGetGroupPowerGrade(model *domain.Model, groupPowerIds []mysql.ID) (map[mysql.ID]GroupPowerGrade, error) {
var rows []GroupPowerGrade
res := make(map[mysql.ID]GroupPowerGrade)
if err := model.DB().Model(GroupPowerGrade{}).Where("group_power_id in ?", groupPowerIds).Find(&rows).Error; err != nil {
model.Log.Errorf("MGetGroupPowerGrade fail:%v", err)
return res, err
}
for i, v := range rows {
res[v.GroupPowerId] = rows[i]
}
return res, nil
}
package groupPower_m
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql"
"git.hilo.cn/hilo-common/utils"
)
type GroupPowerInfo struct {
mysql.Entity
GroupUid string
Name string
Nameplate string
Declaration string
Icon string
Status int
}
func (GroupPowerInfo) TableName() string {
return "group_power"
}
// 批量获取家族信息
func MGetGroupPowerInfoMap(model *domain.Model, groupPowerIds []mysql.ID) (map[mysql.ID]GroupPowerInfo, error) {
var rows []GroupPowerInfo
res := make(map[mysql.ID]GroupPowerInfo)
if err := model.DB().Model(GroupPowerInfo{}).Where("id in ?", groupPowerIds).Find(&rows).Error; err != nil {
model.Log.Errorf("MGetGroupPowerInfo fail:%v", err)
return res, err
}
for i, v := range rows {
rows[i].Icon = utils.MakeFullUrl(rows[i].Icon) // 拼接url
res[v.ID] = rows[i]
}
return res, nil
}
// 批量获取家族成员
func MGetGroupPowerUsers(model *domain.Model, groupPowerIds []mysql.ID) (map[mysql.ID][]*GroupPowerUser, error) {
var users []*GroupPowerUser
res := make(map[mysql.ID][]*GroupPowerUser)
if err := model.DB().Model(GroupPowerUser{}).Where("group_power_id in ?", groupPowerIds).Find(&users).Error; err != nil {
model.Log.Errorf("MGetGroupPowerUsers fail:%v", err)
return res, err
}
for i, v := range users {
res[v.GroupPowerId] = append(res[v.GroupPowerId], users[i])
}
return res, nil
}
// 获取家族成员
func GetGroupPowerUser(model *domain.Model, groupPowerId mysql.ID) ([]*GroupPowerUser, error) {
m, err := MGetGroupPowerUsers(model, []mysql.ID{groupPowerId})
if err != nil {
return nil, err
}
return m[groupPowerId], nil
}
// 分批获取所有家族成员
func BatchGetAllGroupPowerUsers(model *domain.Model, lastId mysql.ID, limit int) ([]mysql.ID, mysql.ID, error) {
var res []GroupPowerUser
var userIds []mysql.ID
var nextLastId mysql.ID
if err := model.DB().Model(GroupPowerUser{}).
Where("id > ?", lastId).Order("id asc").Limit(limit).Find(&res).Error; err != nil {
model.Log.Errorf("BatchGetAllGroupPowerUsers fail:%v", err)
return userIds, 0, err
}
for _, v := range res {
userIds = append(userIds, v.UserId)
nextLastId = v.ID
}
return userIds, nextLastId, nil
}
package groupPower_m
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql"
"gorm.io/gorm"
"hilo-group/common"
"hilo-group/myerr"
"hilo-group/myerr/bizerr"
"time"
)
type GroupPowerApplyJoin struct {
Id uint64 `json:"id"`
UserId uint64 `json:"user_id"`
GroupPowerId uint64 `json:"group_power_id"`
CreatedTime time.Time `json:"created_time"`
UpdatedTime time.Time `json:"updated_time"`
IsAccept int8 `json:"is_accept"`
MgrId uint64 `json:"mgr_id"`
}
func InsertGroupPowerApplyJoin(model *domain.Model, userId, familyId uint64) error {
sql := "insert into group_power_apply_join(user_id,group_power_id,is_accept) " +
"select ?, ?, ? where not exists (select id from group_power_apply_join where user_id=? and group_power_id=? and is_accept=0)"
result := model.Db.Exec(sql, userId, familyId, 0, userId, familyId)
if result.Error != nil {
return myerr.WrapErr(result.Error)
}
if result.RowsAffected <= 0 {
return myerr.WrapErr(bizerr.GroupPowerHaveAlreadyApply)
}
return nil
}
func GetGroupPowerApplyJoin(model *domain.Model, userId, familyId uint64, isAccept int) (*GroupPowerApplyJoin, error) {
res := new(GroupPowerApplyJoin)
db := model.Db.Where(GroupPowerApplyJoin{UserId: userId, GroupPowerId: familyId})
if isAccept != -1 {
db = db.Where("is_accept=?", isAccept)
}
err := db.First(&res).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return nil, nil
} else {
return nil, myerr.WrapErr(err)
}
}
return res, nil
}
func OptGroupPowerApplyJoinById(model *domain.Model, id, mgrId uint64, optType int) error {
err := model.Db.Exec("update group_power_apply_join set is_accept = ?, mgr_id = ? where id=? and is_accept = 0", optType, mgrId, id).Error
if err != nil {
return myerr.WrapErr(err)
}
return nil
}
func AcceptGroupPowerApplyJoin(model *domain.Model, userId, familyId uint64) error {
err := model.Db.Exec("update group_power_apply_join set is_accept = 1 where user_id=? and group_power_id=?", userId, familyId).Error
if err != nil {
return myerr.WrapErr(err)
}
return nil
}
func OptGroupPowerApplyList(model *domain.Model, familyId uint64, pageSize, pageIndex int) ([]*GroupPowerApplyJoin, int, bool, error) {
rows := make([]*GroupPowerApplyJoin, 0)
db := model.Db.Model(GroupPowerApplyJoin{}).Where("group_power_id = ?", familyId).Order("is_accept, created_time desc")
var count int64
err := db.Count(&count).Error
if err != nil {
return nil, 0, false, err
}
err = db.Limit(pageSize).Offset(pageIndex).Find(&rows).Error
if err != nil {
return nil, 0, false, err
}
nextIdx, hasNext := common.PageNext(count, pageIndex, pageSize)
return rows, nextIdx, hasNext, nil
}
func DelGroupPowerApplyJoinNoDeal(model *domain.Model, userId uint64) error {
err := model.Db.Exec("delete from group_power_apply_join where user_id=? and is_accept = 0", userId).Error
if err != nil {
return myerr.WrapErr(err)
}
return nil
}
// 获取家族申请人数
// param: isAccept 0:未审核 1:通过 2:拒绝
func CountGroupPowerApply(model *domain.Model, groupPowerId mysql.ID, isAccept int) (int64, error) {
var cnt int64
if err := model.DB().Model(GroupPowerApplyJoin{}).
Where("group_power_id = ?", groupPowerId).
Where("is_accept = ?", isAccept).Count(&cnt).Error; err != nil {
model.Log.Errorf("CountGroupPowerApply fail:%v", err)
return cnt, err
}
return cnt, nil
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.