role.go 1.78 KB
Newer Older
hujiebin's avatar
hujiebin committed
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
package group_m

import (
	"git.hilo.cn/hilo-common/_const/common"
	"git.hilo.cn/hilo-common/domain"
	"git.hilo.cn/hilo-common/resource/mysql"
	"gorm.io/gorm"
)

type GroupRoles struct {
	mysql.Entity
	UserId    uint64
	ImGroupId string
	Role      common.GroupRoleType
}

type GroupMember struct {
	GroupId string
	UserId  uint64
}

func (gm *GroupMember) Find(db *gorm.DB) ([]GroupMember, error) {
	rows := make([]GroupMember, 0)
	if err := db.Where(gm).Order("created_time DESC").Find(&rows).Error; err != nil {
		return nil, err
	}
	return rows, nil
}

func GetGroupRoleById(model *domain.Model, imGroupId string, userId uint64) (role common.GroupRoleType, err error) {
	role = common.GROUP_VISITOR
	roles, _, err := GetRolesInGroup(model, imGroupId)
	if err != nil {
		return
	}
	for u, r := range roles {
		if u == userId {
			role = r
			return
		}
	}

	isGroupMember, err := IsGroupMember(model.Db, imGroupId, userId)
	if err != nil {
		return
	}
	if isGroupMember {
		role = common.GROUP_MEMBER
	}
	return
}

// 查询群组中所有有角色的成员,由级别高到低、创建时间由早到晚排列
func GetRolesInGroup(model *domain.Model, groupId string) (map[uint64]uint16, []uint64, error) {
	data := make([]GroupRoles, 0)
	err := model.Db.Where(&GroupRoles{ImGroupId: groupId}).Order("role DESC, created_time").Find(&data).Error
	if err != nil {
		return nil, nil, err
	}

	result := make(map[uint64]uint16, 0)
	orders := make([]uint64, 0)
	for _, i := range data {
		orders = append(orders, i.UserId)
		result[i.UserId] = i.Role
	}
	return result, orders, nil
}

func IsGroupMember(db *gorm.DB, groupId string, userId uint64) (bool, error) {
	gm := GroupMember{
		GroupId: groupId,
		UserId:  userId,
	}
	rows, err := gm.Find(db)
	if err != nil {
		return false, err
	}
	return len(rows) > 0, nil
}