ip.go 2.24 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
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
}