group_op.go 14.8 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3
package group_s

import (
hujiebin's avatar
hujiebin committed
4 5 6
	"context"
	"encoding/json"
	"fmt"
hujiebin's avatar
hujiebin committed
7
	"git.hilo.cn/hilo-common/domain"
chenweijian's avatar
chenweijian committed
8
	"git.hilo.cn/hilo-common/mycontext"
9
	"git.hilo.cn/hilo-common/mylogrus"
chenweijian's avatar
chenweijian committed
10
	"git.hilo.cn/hilo-common/resource/config"
hujiebin's avatar
hujiebin committed
11 12 13 14 15
	"git.hilo.cn/hilo-common/resource/mysql"
	"git.hilo.cn/hilo-common/resource/redisCli"
	"git.hilo.cn/hilo-common/rpc"
	"git.hilo.cn/hilo-common/sdk/agora"
	"git.hilo.cn/hilo-common/sdk/tencentyun"
chenweijian's avatar
chenweijian committed
16
	"git.hilo.cn/hilo-common/sdk/trtc"
hujiebin's avatar
hujiebin committed
17 18
	"git.hilo.cn/hilo-common/utils"
	"gorm.io/gorm"
hujiebin's avatar
hujiebin committed
19
	"hilo-group/_const/enum/group_e"
hujiebin's avatar
hujiebin committed
20 21
	"hilo-group/_const/redis_key"
	"hilo-group/cv/property_cv"
22
	"hilo-group/domain/cache/group_c"
hujiebin's avatar
hujiebin committed
23 24
	"hilo-group/domain/cache/tim_c"
	"hilo-group/domain/event/group_ev"
hujiebin's avatar
hujiebin committed
25
	"hilo-group/domain/model/group_m"
hujiebin's avatar
hujiebin committed
26 27 28 29 30 31 32
	"hilo-group/domain/model/noble_m"
	"hilo-group/domain/model/user_m"
	"hilo-group/domain/service/signal_s"
	"hilo-group/myerr"
	"hilo-group/myerr/bizerr"
	"strconv"
	"time"
hujiebin's avatar
hujiebin committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
)

// 创建群组
func (s *GroupService) CreateGroup(userId uint64, g *group_m.GroupInfo) error {
	return s.svc.Transactional(func() error {
		model := domain.CreateModel(s.svc.CtxAndDb)
		if err := group_m.CreateGroup(model, g); err != nil {
			return err
		}
		if err := group_m.CreateGroupRole(model, g.ImGroupId, userId, group_e.GROUP_OWNER); err != nil {
			return err
		}
		return nil
	})
}
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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118

// 退群的一系列操作
func (s *GroupService) LeaveGroup(model *domain.Model, groupId string, userId uint64, externalId string) error {
	//获取用户是否在麦上, 让用户离开麦
	micUser, err := group_m.GetMicUserByExternalId(model, externalId)
	if err != nil {
		return err
	}
	if micUser != nil {
		if err = micUser.LeaveByUser(userId, externalId); err != nil {
			return err
		}
	}

	// 退群后删除管理角色
	if err = group_m.RemoveGroupRole(model, groupId, userId); err != nil {
		mylogrus.MyLog.Warnf("Can't remove group %s user %d's role.", groupId, userId)
	}

	// 退群后删除它(可能)作为经理设置的欢迎语
	gwt := group_m.GroupWelcomeText{}
	if err = gwt.Remove(model.Db, groupId, userId); err != nil {
		mylogrus.MyLog.Warnf("Can't remove group %s user %d's welcome text.", groupId, userId)
	}

	// 退群后删除小闹钟
	groupUser := group_m.GroupUser{Model: model, GroupId: groupId, UserId: userId}
	if err = groupUser.Delete(); err != nil {
		mylogrus.MyLog.Warnf("Can't remove group %s user %d's option.", groupId, userId)
	}

	// 清理相关缓存
	group_c.ClearGroupMemberCount(groupId)
	group_c.RemoveGroupMember(groupId, externalId)

	return nil
}

// 退出永久会员的一系列操作
func (s *GroupService) LeaveGroupMember(model *domain.Model, groupId string, userId uint64, externalId string) error {
	gm := group_m.GroupMember{
		GroupId: groupId,
		UserId:  userId,
	}
	if err := gm.Remove(model.Db); err != nil {
		return err
	}

	// 退群后删除管理角色
	if err := group_m.RemoveGroupRole(model, groupId, userId); err != nil {
		mylogrus.MyLog.Warnf("Can't remove group %s user %d's role.", groupId, userId)
	}

	// 退群后删除它(可能)作为经理设置的欢迎语
	gwt := group_m.GroupWelcomeText{}
	if err := gwt.Remove(model.Db, groupId, userId); err != nil {
		mylogrus.MyLog.Warnf("Can't remove group %s user %d's welcome text.", groupId, userId)
	}

	// 退群后删除小闹钟
	groupUser := group_m.GroupUser{Model: model, GroupId: groupId, UserId: userId}
	if err := groupUser.Delete(); err != nil {
		mylogrus.MyLog.Warnf("Can't remove group %s user %d's option.", groupId, userId)
	}

	// 清理相关缓存
	group_c.ClearGroupMemberCount(groupId)
	group_c.RemoveGroupMember(groupId, externalId)

	return nil
}
hujiebin's avatar
hujiebin committed
119 120

//进入房间, 返回channelId, err
chenweijian's avatar
chenweijian committed
121
func (s *GroupService) GroupIn(userId uint64, externalId string, groupUuid string, password, imei, ip string, provider group_e.GroupProvider, roomId int64) (string, string, error) {
hujiebin's avatar
hujiebin committed
122 123
	var channelId string
	var token string
chenweijian's avatar
chenweijian committed
124
	var rideId uint64
hujiebin's avatar
hujiebin committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
	err := s.svc.Transactional(func() error {
		//检查群组是否存在, 没有真正的domel,直接service上怼
		model := domain.CreateModel(s.svc.CtxAndDb)
		// 群是否被封禁
		banned := group_m.GroupBanned{ImGroupId: groupUuid}
		if err := banned.Get(model); err != gorm.ErrRecordNotFound {
			return bizerr.GroupIsBanned
		}
		var groupInfo group_m.GroupInfo
		if err := model.Db.Where(&group_m.GroupInfo{
			ImGroupId: groupUuid,
		}).First(&groupInfo).Error; err != nil {
			return myerr.WrapErr(err)
		}

		if userId != groupInfo.Owner && len(groupInfo.Password) > 0 && password != groupInfo.Password {
			return bizerr.IncorrectPassword
		}

		//检查群组中是否有拉黑名单
		//var n int64
		//if err := model.Db.Model(&group_m.GroupBlacklist{}).Where(&group_m.GroupBlacklist{
		//	ImGroupId: groupUuid,
		//	UserId:    userId,
		//}).Count(&n).Error; err != nil {
		//	return nil, nil, myerr.WrapErr(err)
		//}
		//if n != 0 {
		//	return nil, nil, bizerr.InBlacklist
		//}
		svip, _ := rpc.GetUserSvip(model, userId)
		if userId != groupInfo.Owner {
			// 是否超管
			isM, err := user_m.IsSuperManager(model, userId)
			if err != nil {
				model.Log.Errorf("GroupIn err:%v", err)
				return myerr.NewSysError("not super manager")
			}
			// 不是超管 且 用户是否在群的黑名单中
			if !isM && group_m.InGroupBlackList(model, groupUuid, imei, ip, userId) {
				if svip.SvipLevel < 6 { // svip6暂时不判断GroupBlackList
					return bizerr.InBlacklist
				}
			}
		}
		//是否被踢出
		if i, err := redisCli.GetRedis().Exists(context.Background(), redis_key.GetGroupKickGroupUuidUserId(groupUuid, userId)).Result(); err != nil {
			return myerr.WrapErr(err)
		} else if i == 0 {
			user, err := user_m.GetUser(model, userId)
			if err != nil {
				return err
			}
chenweijian's avatar
chenweijian committed
178 179 180 181 182 183 184
			if provider == group_e.GroupProvider_TRTC {
				channelId = groupInfo.ChannelId
				token = trtc.CreateGroupTRTCUserSig(userId, config.GetTRTCConfig())
				model.Log.Infof("enter trtc group userId:%v, groupId:%v", userId, groupUuid)
			} else {
				channelId, token, err = agora.CreateGroupAgora(groupInfo.ChannelId, uint32(userId))
			}
hujiebin's avatar
hujiebin committed
185 186 187 188 189 190 191 192 193 194
			if err != nil {
				return err
			} else {
				//加入房间
				group_m.RoomLivingIn(model, groupUuid, userId, externalId, false)

				groupUser, err := group_m.GetGroupUserOrInit(model, groupUuid, userId)
				if err != nil {
					model.Log.Errorf("GroupIn GetGroupUserOrInit err:%v, groupId:%v, userId:%v", err, groupUuid, userId)
				}
hujiebin's avatar
hujiebin committed
195 196 197 198
				if groupUser != nil {
					if err := groupUser.SetRoomInTime().Persistent(); err != nil {
						model.Log.Errorf("GroupIn groupUser Persistent err:%v, groupId:%v, userId:%v", err, groupUuid, userId)
					}
hujiebin's avatar
hujiebin committed
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
				}

				// 发送进群TIM信令。fixme: 应该发在event处理
				isVip, err := user.CheckVip()
				if err != nil {
					return err
				}

				nobleLevel, err := noble_m.GetNobleLevel(mysql.Db, userId)
				if err != nil {
					return err
				}

				type UserParam struct {
					Nick              string     `json:"nick"`
					UserAvatar        string     `json:"userAvatar"`
					IsVip             bool       `json:"isVip"`
					RideId            uint64     `json:"rideId"`
					RideUrl           string     `json:"rideUrl"`
					RideEffectUrl     string     `json:"rideEffectUrl"`
					RidSenderAvatar   string     `json:"ridSenderAvatar"`
					RidReceiverAvatar string     `json:"ridReceiverAvatar"`
					NobleLevel        uint16     `json:"nobleLevel"`
					SvipLevel         int        `json:"svipLevel"`
					Svip              rpc.CvSvip `json:"svip"`
				}

				up := user_m.UserProperty{}
				rides, err := up.BatchGet(mysql.Db, []uint64{userId})
				if err != nil {
					return err
				}

				//rp := res_m.ResProperty{}
				//properties, err := rp.GetAll(mysql.Db)
				properties, err := property_cv.GetExtendedProperty(mysql.Db)
				if err != nil {
					return err
				}
				r := UserParam{
					Nick:              user.Nick,
					UserAvatar:        user.Avatar,
					IsVip:             isVip,
					RideId:            rides[userId],
					RideUrl:           properties[rides[userId]].PicUrl,
					RideEffectUrl:     properties[rides[userId]].EffectUrl, // todo replace ui svga
					RidSenderAvatar:   properties[rides[userId]].SenderAvatar,
					RidReceiverAvatar: properties[rides[userId]].ReceiverAvatar,
					NobleLevel:        nobleLevel,
					Svip:              rpc.CopySimpleSvip(svip),
				}
chenweijian's avatar
chenweijian committed
250
				rideId = r.RideId
hujiebin's avatar
hujiebin committed
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281

				buf, err := json.Marshal(r)
				if err == nil {
					//发送腾讯云IM系统消息
					signal_s.SendSignalMsg(model,
						groupUuid, group_m.GroupSystemMsg{
							MsgId:   group_e.GroupInSignal,
							Source:  user.ExternalId,
							Content: string(buf),
						}, true)
				}

				isMember, _ := group_m.IsGroupMember(model.Db, groupUuid, userId)
				return group_ev.PublishGroupIn(model, &group_ev.GroupInEvent{
					GroupId:    groupUuid,
					UserId:     userId,
					ExternalId: user.ExternalId,
					Nick:       user.Nick,
					Avatar:     user.Avatar,
					IsMember:   isMember,
					IsVip:      isVip,
					NobleLevel: nobleLevel,
				})
			}
		} else {
			return bizerr.GroupInKick
		}
	})
	if err != nil {
		return "", "", err
	} else {
chenweijian's avatar
chenweijian committed
282
		go dealActDataAfterEnterRoom(s.svc.MyContext, userId, rideId, roomId)
hujiebin's avatar
hujiebin committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
		return channelId, token, nil
	}
}

func (s *GroupService) JoinGroup(userId uint64, externalId string, groupId string) error {
	model := domain.CreateModel(s.svc.CtxAndDb)
	model.Log.Infof("Async: user %d(%s) is joining group %s", userId, externalId, groupId)

	for i := 1; i < 3; i++ {
		info, err, errCode := tencentyun.AddGroup(model, groupId, []string{externalId})
		if err == nil && info != nil {
			for i, r := range info {
				if i == externalId {
					if r == group_e.ADD_GROUP_DONE || r == group_e.ADD_GROUP_DUPLICATE {
						// 加群成功后,马上发送通知给客户端,让他们拉取历史消息
						err = rpc.SendJoinGroup(userId, externalId, groupId)
						model.Log.Infof("joinGroup: SendJoinGroup err = %v", err)
					}

					if r == group_e.ADD_GROUP_DONE {
						group_c.ClearGroupMemberCount(groupId)
						tim_c.AddGroupMember(model, groupId, externalId)
					}
				}
				return nil
			}
		} else if errCode == 10014 || errCode == 10038 {
			// 如果群成员达到上限,删除一个(10014 达到群上限;10038 达到APP上限)
			extId, err := s.RemoveZombie(model, groupId)
			if err != nil {
				return err
			}
			model.Log.Infof("JoinGroup %s limit reached, errCode = %d, %s kicked", groupId, errCode, extId)
		}

	}
	return fmt.Errorf("failed 3 times")
}

// 清除TIM群的僵尸
func (s *GroupService) RemoveZombie(model *domain.Model, groupId string) (string, error) {
	rows, err := group_m.GetMembers(model.Db, groupId)
	if err != nil {
		return "", err
	}
	userIds := make([]uint64, 0)
	for _, i := range rows {
		userIds = append(userIds, i.UserId)
	}
	model.Log.Infof("JoinGroup %s: members: %v", groupId, userIds)

	roomUids, err := group_m.RoomLivingExistsUserId(groupId)
	if err != nil {
		return "", err
	}
	model.Log.Infof("JoinGroup %s: roomUids: %v", groupId, roomUids)

	userIds = append(userIds, roomUids...)
	userIds = utils.UniqueSliceUInt64(userIds)

	m, err := user_m.GetUserMapByIds(model, userIds)
	if err != nil {
		return "", err
	}
	extIdsMap := make(map[string]uint64)
	for _, i := range m {
		extIdsMap[i.ExternalId] = i.ID
	}
	model.Log.Infof("JoinGroup %s: extIdsMap: %v", groupId, extIdsMap)

	_, gm, err := tencentyun.GetGroupMemberInfo(model, groupId)
	if err != nil {
		return "", err
	}

	zombie := ""
	for _, i := range gm {
		if _, ok := extIdsMap[i.Member_Account]; !ok {
			model.Log.Infof("JoinGroup %s: to kick %s", groupId, i.Member_Account)

			tencentyun.LeaveGroup(groupId, []string{i.Member_Account})
			zombie = i.Member_Account
			break
		}
	}
	return zombie, nil
}

//离开房间
func (s *GroupService) GroupLeave(userId uint64, externalId string, groupId string) error {
	model := domain.CreateModelContext(s.svc.MyContext)

	_, err := group_m.RoomLivingLeave(model, userId, externalId, groupId)
	return err
}

//踢人
func (s *GroupService) GroupKick(groupUuid string, userId uint64, userExternalId string, userNick string, avatar string, beKickUserId uint64, beKickExternalId string, beKickUserNick string, beKickUserAvatar string) error {
	return s.svc.Transactional(func() error {
		model := domain.CreateModel(s.svc.CtxAndDb)
		//木有model层给我,直接server怼了

		//被踢的人不能是超级管理人
		if flag, err := user_m.IsSuperManager(model, beKickUserId); err != nil {
			return err
		} else if flag {
			return bizerr.OfficialStaffLimit
		}

		//超级管理人,无敌状态
		if flag, err := user_m.IsSuperManager(model, userId); err != nil {
			return err
		} else if !flag {
			//判断权限
			if err := group_m.MgrPermission(model, groupUuid, userId, beKickUserId); err != nil {
				return err
			}
			//检查是否是贵族
			if flag, err := noble_m.CheckNobleLevel(model.Db, beKickUserId, 5); err != nil {
				return err
			} else if flag {
				return bizerr.NobleNoKickLevel5
			}
		}
		//踢人10分钟
		_, err := redisCli.GetRedis().Set(context.Background(), redis_key.GetGroupKickGroupUuidUserId(groupUuid, beKickUserId), strconv.Itoa(int(beKickUserId)), time.Minute*10).Result()
		if err != nil {
			return myerr.WrapErr(err)
		}

		//删除房间中redis
		//group_m.RoomLivingLeave(model, groupUuid, beKickUserId)
		group_m.RoomLivingLeaveByKick(model, groupUuid, beKickUserId, beKickExternalId, userExternalId)
		// 发信令,让前端重新拉取,接受容错,
		/*		SendSignalMsg(groupUuid, group_m.GroupSystemMsg{
				MsgId:  group_m2.GroupKickOut,
				Source: userExternalId,
				Target: beKickExternalId,
			})*/

		//记录踢人(非事务性, 错误不进行处理)
		if err := group_m.AddGroupKickRecord(model, groupUuid, userId, beKickUserId); err != nil {
			model.Log.Errorln(err)
		}

		/*		//获取用户是否在麦上, 让用户离开麦
				micUser, err := group_m.GetMicUserByExternalId(model, beKickExternalId)
				if err != nil {
					return nil, nil, err
				}
				if micUser != nil {
					micUser.LeaveByUser(userId, userExternalId)
				}*/

		return group_ev.PublishGroupKickOut(model, &group_ev.GroupKickOutEvent{
			GroupId:            groupUuid,
			OperatorExternalId: userExternalId,
			OperatorName:       userNick,
			OperatorFaceUrl:    avatar,
			MemberExternalId:   beKickExternalId,
			MemberName:         beKickUserNick,
			MemberAvatar:       beKickUserAvatar,
		})
	})
}

// 群管理人清理公屏
func (s *GroupService) GroupClearScreenByMgr(groupId string, userId uint64) error {
	model := domain.CreateModelContext(s.svc.MyContext)
	//检查权限
	if err := group_m.CheckPermission(model, groupId, userId); err != nil {
		return err
	}
	systemMsg := group_m.GroupSystemMsg{MsgId: group_e.GroupClearScreen, Source: "", Content: ""}
	signal_s.SendSignalMsg(model, groupId, systemMsg, false)
	return nil
}
chenweijian's avatar
chenweijian committed
460 461 462 463 464 465 466 467

func dealActDataAfterEnterRoom(myContext *mycontext.MyContext, userId, rideId uint64, roomId int64) {
	defer utils.CheckGoPanic()
	if rideId == 1261 {
		// 处理活动数据
		go rpc.AddActPoint(domain.CreateModelContext(myContext), userId, 5, roomId)
	}
}