package user_m import ( "git.hilo.cn/hilo-common/domain" "git.hilo.cn/hilo-common/resource/mysql" "gorm.io/gorm" "hilo-group/myerr" "time" ) //用户IP type UserIp struct { mysql.Entity *domain.Model `gorm:"-"` UserId mysql.ID Ip mysql.Str } func GetUserIpOrInit(model *domain.Model, userId mysql.ID) (*UserIp, error) { var userIp UserIp if err := model.Db.Where(&UserImei{ UserId: userId, }).First(&userIp).Error; err != nil { if err == gorm.ErrRecordNotFound { userIp.UserId = userId } else { return nil, myerr.WrapErr(err) } } userIp.Model = model return &userIp, nil } func GetUserIpMap(db *gorm.DB, userIds []uint64) (map[uint64]string, error) { rows := make([]UserIp, 0) if err := db.Model(&UserIp{}).Where("user_id IN ?", userIds).Find(&rows).Error; err != nil { return nil, myerr.WrapErr(err) } // userIpMap := map[uint64]string{} for _, i := range rows { userIpMap[i.UserId] = i.Ip } return userIpMap, nil } //更新Ip func (userIp *UserIp) UpdateIp(ip string) *UserIp { userIp.Ip = ip return userIp } //统计imei数量 func countIp(model *domain.Model, ip string, beginTime time.Time) (int64, error) { var c int64 = 0 if err := model.Db.Model(&UserIp{}).Where(&UserIp{ Ip: ip, }).Where("created_time >= ?", beginTime).Count(&c).Error; err != nil { return 0, myerr.WrapErr(err) } return c, nil } func IpUserIds(model *domain.Model, ip string) ([]uint64, error) { rows := []UserIp{} if err := model.Db.Model(&UserIp{}).Where(&UserIp{ Ip: ip, }).Find(&rows).Error; err != nil { return nil, myerr.WrapErr(err) } userIds := make([]uint64, 0, len(rows)) for _, i := range rows { userIds = append(userIds, i.UserId) } return userIds, nil } func GetSameIpUsers(model *domain.Model, userId uint64) ([]uint64, error) { userIp, err := GetUserIpOrInit(model, userId) if err != nil { return nil, err } userIds, err := IpUserIds(model, userIp.Ip) if err != nil { return nil, err } return userIds, nil } func GetSameIpUsersMap(model *domain.Model, userId uint64) (map[uint64]struct{}, error) { rec, err := GetSameIpUsers(model, userId) if err != nil { return nil, err } result := make(map[uint64]struct{}, 0) for _, i := range rec { result[i] = struct{}{} } return result, nil }