group_op.go 42.2 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3
package group_r

import (
hujiebin's avatar
hujiebin committed
4
	"encoding/json"
hujiebin's avatar
hujiebin committed
5 6
	"git.hilo.cn/hilo-common/domain"
	"git.hilo.cn/hilo-common/mycontext"
7
	"git.hilo.cn/hilo-common/mylogrus"
hujiebin's avatar
hujiebin committed
8
	"git.hilo.cn/hilo-common/resource/config"
9
	"git.hilo.cn/hilo-common/resource/mysql"
hujiebin's avatar
hujiebin committed
10 11
	"git.hilo.cn/hilo-common/resource/redisCli"
	"git.hilo.cn/hilo-common/sdk/agora"
hujiebin's avatar
hujiebin committed
12
	"git.hilo.cn/hilo-common/sdk/aws"
hujiebin's avatar
hujiebin committed
13 14 15 16 17
	"git.hilo.cn/hilo-common/sdk/tencentyun"
	"git.hilo.cn/hilo-common/utils"
	"github.com/gin-gonic/gin"
	uuid "github.com/satori/go.uuid"
	"gorm.io/gorm"
hujiebin's avatar
hujiebin committed
18
	"hilo-group/_const/enum/diamond_e"
hujiebin's avatar
hujiebin committed
19 20
	"hilo-group/_const/enum/group_e"
	"hilo-group/_const/enum/msg_e"
21 22
	"hilo-group/_const/enum/online_e"
	"hilo-group/_const/enum/user_e"
hujiebin's avatar
hujiebin committed
23 24 25 26 27
	"hilo-group/_const/redis_key/group_k"
	"hilo-group/cv/billboard_cv"
	"hilo-group/cv/gift_cv"
	"hilo-group/cv/group_cv"
	"hilo-group/cv/user_cv"
hujiebin's avatar
hujiebin committed
28
	"hilo-group/domain/cache/group_c"
hujiebin's avatar
hujiebin committed
29
	"hilo-group/domain/cache/res_c"
hujiebin's avatar
hujiebin committed
30
	"hilo-group/domain/model/diamond_m"
hujiebin's avatar
hujiebin committed
31
	"hilo-group/domain/model/group_m"
32
	"hilo-group/domain/model/noble_m"
hujiebin's avatar
hujiebin committed
33
	"hilo-group/domain/model/res_m"
34
	"hilo-group/domain/model/tim_m"
hujiebin's avatar
hujiebin committed
35 36
	"hilo-group/domain/model/user_m"
	"hilo-group/domain/service/group_s"
hujiebin's avatar
hujiebin committed
37
	"hilo-group/domain/service/signal_s"
hujiebin's avatar
hujiebin committed
38 39 40 41
	"hilo-group/myerr"
	"hilo-group/myerr/bizerr"
	"hilo-group/req"
	"hilo-group/resp"
42 43
	"math"
	"runtime/debug"
hujiebin's avatar
hujiebin committed
44
	"sort"
hujiebin's avatar
hujiebin committed
45
	"strconv"
hujiebin's avatar
hujiebin committed
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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 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
	"strings"
	"time"
)

type CreateGroupRsp struct {
	ImGroupId string `json:"imGroupId"`
	Code      string `json:"code"`
}

// @Tags 群组
// @Summary 建群
// @Accept application/x-www-form-urlencoded
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param name formData string false "群名"
// @Param introduction formData string false "群简介"
// @Param notification formData string false "群公告"
// @Param faceUrl formData string false "群头像 URL"
// @Success 200 {object} CreateGroupRsp
// @Router /v1/imGroup/group [post]
func CreateGroup(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)

	userId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}
	if lock := redisCli.Lock(group_k.GetGroupLockKey(userId), time.Second*5); !lock {
		return myContext, bizerr.ReqTooFrequent
	}

	model := domain.CreateModelContext(myContext)

	user, err := user_m.GetUser(model, userId)
	if err != nil {
		return myContext, err
	}

	// Kludge: 不支持的语言,强行修正为英语,以保证建群成功
	if c, err := res_m.GetCountryByLanguage(model, user.Language); err != nil || c == nil {
		user.Language = utils.DEFAULT_LANG
	}

	// 群组的头像默认为用户头像,群组的名称默认为用户昵称,群简介默认为“s%的群组”,群公告默认为“欢迎来到Hilo”
	name := c.PostForm("name")
	if len(name) <= 0 {
		text := res_m.ResMultiText{MsgId: msg_e.MSG_ID_GROUP_NAME, Language: user.Language}
		if text.Get(model.Db) == nil {
			name = strings.ReplaceAll(text.Content, "{nick}", user.Nick)
		}
	}

	introduction := c.PostForm("introduction")
	if len(introduction) <= 0 {
		text := res_m.ResMultiText{MsgId: msg_e.MSG_ID_GROUP_INTRODUCTION, Language: user.Language}
		if text.Get(model.Db) == nil {
			introduction = strings.ReplaceAll(text.Content, "{nick}", user.Nick)
		}
	}
	notification := c.PostForm("notification")
	if len(notification) <= 0 {
		text := res_m.ResMultiText{MsgId: msg_e.MSG_ID_GROUP_NOTIFICATION, Language: user.Language}
		if text.Get(model.Db) == nil {
			notification = strings.ReplaceAll(text.Content, "{nick}", user.Nick)
		}
	}
	faceUrl := c.PostForm("faceUrl")
	if len(faceUrl) <= 0 {
		faceUrl = user.Avatar
	}

	myGroups, err := group_m.FindGroupByOwner(model, userId)
	if err != nil {
		return nil, err
	}
	// Kludge: 对超级号放开建群限制
	if !user_m.IsSuperUser(userId) && len(myGroups) >= group_e.GROUP_CREATE_LIMIT {
		return myContext, bizerr.GroupCreateLimitReached
	}

	code := group_m.GenerateGroupCode(group_e.GROUP_DEFAULT_CODE_LENGTH)
	i := 0
	for ; i < group_e.CREATE_GROUP_MAX_ATTEMPT; i++ {
		success, err := res_m.CheckCode(model, code)
		if err != nil || !success {
			break
		}
		r, err := group_m.FindGroupByCode(model, code)
		if err == nil && r == nil {
			break
		}
		code = group_m.GenerateGroupCode(group_e.GROUP_DEFAULT_CODE_LENGTH)
	}

	if i >= group_e.CREATE_GROUP_MAX_ATTEMPT {
		return myContext, myerr.NewSysError("Failed in generating groupId")
	}

	groupId := group_e.OverseaGroupNamePrefix + code
	groupId, err = tencentyun.CreateGroup(name, groupId)
	if err != nil {
		return myContext, err
	}

	channelId := getUUID()
	_, _, err = agora.CreateGroupAgora(channelId, uint32(userId))

	if err != nil {
		// 回滚,删除刚刚建立的TX群组
		tencentyun.DestroyGroup(groupId, false)
		return myContext, err
	}

	roomType := group_e.OverseaRoom
	g := group_m.GroupInfo{
		ImGroupId:      groupId,
		TxGroupId:      groupId,
		Type:           uint16(roomType),
		Code:           code,
		OriginCode:     code,
		Owner:          userId,
		Name:           name,
		Introduction:   introduction,
		Notification:   notification,
		FaceUrl:        faceUrl,
		Country:        user.Country,
		ChannelId:      channelId,
		MicOn:          true,
		LoadHistory:    false,
		MicNumType:     group_e.TenMicNumType,
		TouristMic:     1,
		TouristSendMsg: 1,
		TouristSendPic: 1,
	}
	if err := group_s.NewGroupService(myContext).CreateGroup(userId, &g); err != nil {
		// 回滚,删除刚刚建立的TX群组
		tencentyun.DestroyGroup(groupId, false)
		return myContext, err
	}

	gm := group_m.GroupMember{
		GroupId: groupId,
		UserId:  userId,
	}
	if err = gm.Create(model.Db); err != nil {
		model.Log.Warnf("Failed to set GroupMember +%v", gm)
	}

	resp.ResponseOk(c, CreateGroupRsp{ImGroupId: groupId, Code: code})
	return myContext, nil
}

func getUUID() string {
	return strings.Replace(uuid.NewV4().String(), "-", "", -1)
}

// @Tags 群组
// @Summary 撤群
// @Accept application/x-www-form-urlencoded
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param groupId path string true "群ID"
// @Success 200
// @Router /v1/imGroup/group/{groupId} [delete]
func DestroyGroup(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)

	groupId := c.Param("groupId")
	if len(groupId) <= 0 {
		return myContext, myerr.NewSysError("groupId 为必填项")
	}

	userId, _, err := req.GetUserIdAndExtId(c, myContext)
	if err != nil {
		return myContext, err
	}

	if !user_m.IsSuperUser(userId) {
		return myContext, bizerr.NoPrivileges
	}

	// 参数已经是TxGroupId,不需要再转换了
	err = tencentyun.DestroyGroup(groupId, false)
	if err != nil {
		return myContext, err
	}

	resp.ResponseOk(c, groupId)
	return myContext, nil
}

// @Tags 群组
// @Summary 查询群信息(运营用)
// @Accept application/x-www-form-urlencoded
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param code path string true "群CODE"
hujiebin's avatar
hujiebin committed
243
// @Success 200 {object} group_cv.GroupInfo
hujiebin's avatar
hujiebin committed
244 245 246 247 248 249 250 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 282 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
// @Router /v1/imGroup/group/{code} [get]
func GetGroupInfo(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)

	code := c.Param("code")
	if len(code) <= 0 {
		return myContext, myerr.NewSysError("code 为必填项")
	}

	model := domain.CreateModelContext(myContext)

	r, err := group_m.FindGroupByCode(model, code)
	if r == nil {
		return myContext, bizerr.GroupNotFound
	}

	groupInfo, err := tencentyun.GetGroupInfo(model, []string{r.ImGroupId}, true)
	if err != nil {
		return myContext, err
	}
	if len(groupInfo) < 1 {
		return myContext, myerr.NewSysError("ImGroupId does not exists.")
	}
	info := &groupInfo[0]

	countryInfo, err := res_c.GetCountryIconMap(model)
	if err != nil {
		return myContext, err
	}

	result := group_cv.GroupInfo{
		GroupBasicInfo: group_cv.GroupBasicInfo{
			GroupId:         r.TxGroupId,
			Name:            r.Name,
			Introduction:    r.Introduction,
			Notification:    r.Notification,
			FaceUrl:         r.FaceUrl,
			Owner_Account:   info.Owner_Account,
			CreateTime:      info.CreateTime,
			LastMsgTime:     info.LastMsgTime,
			NextMsgSeq:      info.NextMsgSeq,
			MemberNum:       info.MemberNum,
			MaxMemberNum:    info.MaxMemberNum,
			ShutUpAllMember: info.ShutUpAllMember,
			Code:            r.Code,
			CountryIcon:     countryInfo[r.Country],
			MicNumType:      int(r.MicNumType),
		},
	}

	for _, i := range info.MemberList {
		result.MemberList = append(result.MemberList, group_cv.MemberListInfo{
			Member_Account:  i.Member_Account,
			JoinTime:        i.JoinTime,
			LastSendMsgTime: i.LastSendMsgTime,
		})
	}

	resp.ResponseOk(c, result)
	return myContext, nil
}

// @Tags 群组
// @Summary 查询群详细信息
// @Accept application/x-www-form-urlencoded
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param groupId path string true "群ID"
hujiebin's avatar
hujiebin committed
312
// @Success 200 {object} group_cv.GroupDetail
hujiebin's avatar
hujiebin committed
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
// @Router /v1/imGroup/detail/{groupId} [get]
func GetGroupDetail(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)

	groupId := c.Param("groupId")
	if len(groupId) <= 0 {
		return myContext, myerr.NewSysError("groupId 为必填项")
	}

	myUserId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}

	model := domain.CreateModelContext(myContext)

	groupInfo, err := group_m.GetInfoByTxGroupId(model, groupId)
	if err != nil {
		return myContext, err
	}
	if groupInfo == nil {
		return myContext, bizerr.GroupNotFound
	}
	groupId = groupInfo.ImGroupId

	memberCount, err := group_m.GetMemberCount(model.Db, groupId)
	if err != nil {
		return myContext, err
	}

	countryInfo, err := res_c.GetCountryIconMap(model)
	if err != nil {
		return myContext, err
	}

	themeUrl := ""
	var themeId uint64 = 0
	var themeType uint8 = 1
	if groupInfo.ThemeId > 0 {
		//官方主题
		// 找不到的,默认为空(可能被后台删了)
		themeType = 1
		themes, _ := res_m.GroupThemeGetAll(model.Db)
		for _, i := range themes {
			if i.ID == uint64(groupInfo.ThemeId) {
				themeUrl = i.Url
				themeId = i.ID
				break
			}
		}
	} else {
		//可能是自定义主题
		themeId, themeUrl, err = group_m.GetShowCustomTheme(model, groupInfo.ImGroupId)
		if err != nil {
			return myContext, err
		}
		if themeId != 0 {
			themeType = 2
		}
	}

	result := group_cv.GroupDetail{
		GroupBasicInfo: group_cv.GroupBasicInfo{
			GroupId:        groupInfo.TxGroupId,
			Name:           groupInfo.Name,
			Introduction:   groupInfo.Introduction,
			Notification:   groupInfo.Notification,
			FaceUrl:        groupInfo.FaceUrl,
			MemberNum:      memberCount,
			Code:           groupInfo.Code,
			CountryIcon:    countryInfo[groupInfo.Country],
			MicNumType:     int(groupInfo.MicNumType),
			TouristMic:     groupInfo.TouristMic,
			TouristSendMsg: groupInfo.TouristSendMsg,
			TouristSendPic: groupInfo.TouristSendPic,
			MemberFee:      groupInfo.MemberFee,
		},
		MicOn:       groupInfo.MicOn,
		LoadHistory: groupInfo.LoadHistory,
		ThemeId:     themeId,
		ThemeUrl:    themeUrl,
		ThemeType:   themeType,
		Role:        group_e.GROUP_VISITOR,
	}

	result.TotalConsume, err = gift_cv.GetGroupConsumeTotal(model, groupId)
	if err != nil {
		return myContext, err
	}

	model.Log.Infof("GetGroupDetail, before GetGroupTop3Consume: +%v", result)
	result.TopConsumers, err = billboard_cv.GetGroupTop3Consume(model, groupId, myUserId)
	if err != nil {
		return myContext, err
	}
	model.Log.Infof("GetGroupDetail, after GetGroupTop3Consume: +%v", result)

hujiebin's avatar
hujiebin committed
410
	result.WelcomeText, _, _, err = group_s.NewGroupService(myContext).GetWelcomeText(groupInfo)
hujiebin's avatar
hujiebin committed
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 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
	if err != nil {
		return myContext, err
	}
	result.WelcomeText = strings.ReplaceAll(result.WelcomeText, "@%s", "")

	result.DiceNum = group_e.GROUP_DICE_NUM_DEFAULT
	result.DiceType = 1
	gs := group_m.GroupSetting{GroupId: groupId}
	err = gs.Get(model.Db)
	if err == nil {
		result.DiceNum = gs.DiceNum
		result.DiceType = gs.DiceType
	} else if err != gorm.ErrRecordNotFound {
		return myContext, err
	}

	roles, _, err := group_m.GetRolesInGroup(model, groupInfo.ImGroupId)
	if err != nil {
		return myContext, err
	}

	userId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}

	isGroupMember, err := group_m.IsGroupMember(model.Db, groupId, userId)
	if err != nil {
		return myContext, err
	}
	if isGroupMember {
		result.Role = group_e.GROUP_MEMBER
	}

	groupUser := group_m.GroupUser{Model: model, UserId: userId}
	msgStatus, err := groupUser.Get()
	if err != nil {
		return myContext, err
	}

	// 默认为免打扰
	ok := false
	if result.MsgStatus, ok = msgStatus[groupId]; !ok {
		//result.MsgStatus = group_enum.DoNotDisturbMsgStatusGroupUser
		result.MsgStatus = group_e.NormalMsgStatusGroupUser
	}

	emptyStr := ""
	if len(groupInfo.Password) > 0 {
		// 代表有密码
		result.Password = &emptyStr
	}

	userIds := make([]uint64, 0)
	for u, r := range roles {
		userIds = append(userIds, u)

		if u == userId {
			if r == group_e.GROUP_OWNER || r == group_e.GROUP_MANAGER {
				// 如果用户是OW或经理,可以看到密码,同时设置角色
				result.Role = r

				if len(groupInfo.Password) > 0 {
					result.Password = &groupInfo.Password
				}
			} else if r == group_e.GROUP_ADMIN {
				// 如果用户是管理员,仅设置角色
				result.Role = r
			}
		}
	}
	userIds = append(userIds, groupInfo.Owner)
	users, err := user_cv.GetUserTinyMap(userIds)
	if err != nil {
		return myContext, err
	}
	result.Owner, err = user_cv.GetUserDetail(model, groupInfo.Owner, userId)
	if err != nil {
		return myContext, err
	}

	vips, err := user_m.BatchGetVips(userIds)
	if err != nil {
		return myContext, myerr.WrapErr(err)
	}

	//extIds := make([]string, 0)
	//for _, i := range users {
	//	extIds = append(extIds, i.ExternalId)
	//}
	/* fixme:为了性能,直接不查IM在线状态
	   status, err := tim_m.GetOnlineStatus(model, extIds)
	   if err != nil {
	   	return myContext, err
	   }
	*/
hujiebin's avatar
hujiebin committed
507
	superManagerMap, err := user_m.GetSuperManagerMap(userIds)
hujiebin's avatar
hujiebin committed
508 509 510 511 512 513 514 515
	if err != nil {
		return myContext, err
	}

	status := make(map[string]uint, 0)

	for u, _ := range users {
		m := users[u]
hujiebin's avatar
hujiebin committed
516 517
		result.RoleMembers = append(result.RoleMembers, group_cv.RoleMemberInfo{
			CvUserBase: user_cv.CvUserBase{
hujiebin's avatar
hujiebin committed
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
				Avatar:          &m.Avatar,
				ExternalId:      &m.ExternalId,
				Nick:            &m.Nick,
				Sex:             &m.Sex,
				Country:         &m.CountryIcon,
				CountryIcon:     &m.CountryIcon,
				Code:            &m.Code,
				IsPrettyCode:    m.IsPrettyCode,
				IsVip:           vips[m.Id] != nil,
				IsOfficialStaff: superManagerMap[m.Id],
				VipExpireTime:   vips[m.Id],
			},
			Role:         roles[u],
			OnlineStatus: status[m.ExternalId],
		})
	}

	sort.SliceStable(result.RoleMembers, func(i, j int) bool {
		if result.RoleMembers[i].Role > result.RoleMembers[j].Role {
			return true
		} else if result.RoleMembers[i].Role == result.RoleMembers[j].Role {
			if result.RoleMembers[i].OnlineStatus > result.RoleMembers[j].OnlineStatus {
				return true
			} else if result.RoleMembers[i].OnlineStatus == result.RoleMembers[j].OnlineStatus && *result.RoleMembers[i].Code > *result.RoleMembers[j].Code {
				return true
			}
		}
		return false
	})

	// 截取前N个
hujiebin's avatar
hujiebin committed
549
	endPos := group_e.GROUP_ROLE_VIEW_LIMIT
hujiebin's avatar
hujiebin committed
550 551 552 553 554 555
	if endPos > len(result.RoleMembers) {
		endPos = len(result.RoleMembers)
	}
	result.RoleMembers = result.RoleMembers[0:endPos]

	// todo: 直接用全量接口,只为方便
hujiebin's avatar
hujiebin committed
556
	supportLevels, err := group_s.NewGroupService(myContext).GetWeekMaxSupportLevelMap()
hujiebin's avatar
hujiebin committed
557 558 559 560 561 562
	if err != nil {
		return myContext, err
	}

	result.SupportLevel = supportLevels[groupId]

hujiebin's avatar
hujiebin committed
563
	resp.ResponseOk(c, result)
hujiebin's avatar
hujiebin committed
564 565
	return myContext, nil
}
hujiebin's avatar
hujiebin committed
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835

// @Tags 群组
// @Summary 修改群信息
// @Accept application/x-www-form-urlencoded
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param groupId path string true "群ID"
// @Param name formData string false "群名"
// @Param introduction formData string false "群简介"
// @Param notification formData string false "群公告"
// @Param faceUrl formData string false "群头像 URL"
// @Param password formData string false "入群密码"
// @Param micOn formData bool false "是否打开麦位"
// @Param loadHistory formData bool false "入群后是否加载历史"
// @Param themeId formData int false "群组背景ID"
// @Param welcomeText formData string false "入群欢迎语"
// @Param diceNum formData uint16 false "骰子数量"
// @Param diceType formData int false "骰子类型 1:数字0-9 2:数字1-6"
// @Param touristMic formData int false "游客是否能上麦(1是2否,不传则不改变)"
// @Param touristSendMsg formData int false "游客是否是否能发言(1是2否,不传则不改变)"
// @Param touristSendPic formData int false "游客是否能发图片(1是2否,不传则不改变)"
// @Param isChangeFee formData int false "是否更改加入群组需要的黄钻数,0否1是(兼容旧版本)"
// @Param memberFee formData int false "加入群组需要的黄钻数"
// @Success 200
// @Router /v1/imGroup/group/{groupId} [put]
func ModifyGroupInfo(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)

	imGroupId := c.Param("groupId")
	if len(imGroupId) <= 0 {
		return myContext, myerr.NewSysError("groupId为必填项")
	}

	userId, externalId, err := req.GetUserIdAndExtId(c, myContext)
	if err != nil {
		return myContext, err
	}

	model := domain.CreateModelContext(myContext)

	imGroupId, err = group_m.ToImGroupId(model, imGroupId)
	if err != nil {
		return myContext, err
	}

	// 判断有没有权限修改资料
	role, err := group_m.GetRoleInGroup(model, userId, imGroupId)
	if err != nil {
		return myContext, err
	}
	if role != group_e.GROUP_OWNER && role != group_e.GROUP_MANAGER {
		return myContext, bizerr.NoPrivileges
	}
	groupInfo, err := group_m.GetGroupInfo(model, imGroupId)
	if err != nil {
		return myContext, err
	}
	diamondAccount, err := diamond_m.GetDiamondAccountByUserId(model, groupInfo.Owner)
	if err != nil {
		return myContext, err
	}
	if diamondAccount.Status == diamond_e.Frozen {
		// 如果已经冻结,则不能操作
		return myContext, bizerr.NoPrivileges
	}
	type signalMsg struct {
		Name         *string `json:"name"`
		Introduction *string `json:"introduction"`
		Notification *string `json:"notification"`
		FaceUrl      *string `json:"faceUrl"`
		MicOn        *bool   `json:"micOn"`
		MicNumType   *group_e.GroupMicNumType
		ThemeId      *int16  `json:"themeId"`
		ThemeUrl     *string `json:"themeUrl"`
		//1: 官方 2:自定义
		ThemeType      *uint8  `json:"themeType"`
		TouristMic     *uint8  `json:"touristMic"`     // 游客是否能上麦1是2否
		TouristSendMsg *uint8  `json:"touristSendMsg"` // 游客是否能发消息1是2否
		TouristSendPic *uint8  `json:"touristSendPic"` // 游客是否能发图片1是2否
		MemberFee      *uint64 `json:"memberFee"`      // 加入会员需要黄钻数
	}
	signal := signalMsg{}
	fields := make([]string, 0)
	name, exists := c.GetPostForm("name")
	if exists {
		fields = append(fields, "name")
		signal.Name = &name

		// 2022-04-06 官方群组不能通过客户端修改名称和头像
		if group_m.IsOfficialGroup(imGroupId) {
			return myContext, bizerr.NoPrivileges
		}
	}

	introduction, exists := c.GetPostForm("introduction")
	if exists {
		fields = append(fields, "introduction")
		signal.Introduction = &introduction
	}
	notification, exists := c.GetPostForm("notification")
	if exists {
		fields = append(fields, "notification")
		signal.Notification = &notification
	}
	g := group_m.GroupInfo{
		Name:         name,
		Introduction: introduction,
		Notification: notification,
	}

	faceUrl, exists := c.GetPostForm("faceUrl")
	welcomeText := c.PostForm("welcomeText")

	// 编辑cd
	if len(name) > 0 || len(introduction) > 0 || len(notification) > 0 || len(faceUrl) > 0 || len(welcomeText) > 0 {
		if group_c.IsEditGroupCd(model, imGroupId) {
			return myContext, bizerr.EditCd
		}
	}
	if exists {
		// 2022-04-06 官方群组不能通过客户端修改名称和头像
		if group_m.IsOfficialGroup(imGroupId) {
			return myContext, bizerr.NoPrivileges
		}

		// 2022-06-20 HL限制1115,1116群组改群头像
		/*		if imGroupId == "@TGS#3LXQ2TWH3" || imGroupId == "@TGS#3LICQDVHM" {
					return myContext, bizerr.NoPrivileges
				}
		*/
		if len(faceUrl) > 0 {
			g.FaceUrl = utils.MakeFullUrl(faceUrl)

			switch config.GetConfigApp().MODERATE {
			case "AWS":
				passed, err := aws.ModerateLabels(model.Log, userId, faceUrl)
				if err == nil {
					if !passed {
						return myContext, bizerr.ImagePolicyViolation
					}
				} else {
					model.Log.Warnf("ModerateLabels err:%v", err)
				}
			case "TENCENT":
				label, err := tencentyun.ModerateImage(model, userId, "", faceUrl, g.FaceUrl)
				if err == nil && label != "Pass" {
					return myContext, bizerr.ImagePolicyViolation
				}
			}
		}
		fields = append(fields, "face_url")
		signal.FaceUrl = &g.FaceUrl
	}

	password, exists := c.GetPostForm("password")
	if exists {
		if len(password) > 0 && len(password) != group_e.ROOM_PASSWORD_LENGTH {
			return myContext, bizerr.WrongPasswordLength
		}
		g.Password = password
		fields = append(fields, "password")
	}

	if micOn, err := strconv.ParseBool(c.PostForm("micOn")); err == nil {
		g.MicOn = micOn

		fields = append(fields, "mic_on")
		signal.MicOn = &g.MicOn
	}

	if loadHistory, err := strconv.ParseBool(c.PostForm("loadHistory")); err == nil {
		g.LoadHistory = loadHistory

		fields = append(fields, "load_history")
	}

	if touristMic, err := strconv.ParseInt(c.PostForm("touristMic"), 10, 16); err == nil && touristMic > 0 && touristMic < 3 {
		g.TouristMic = uint8(touristMic)
		fields = append(fields, "tourist_mic")
		signal.TouristMic = &g.TouristMic
	}
	if touristSendMsg, err := strconv.ParseInt(c.PostForm("touristSendMsg"), 10, 16); err == nil && touristSendMsg > 0 && touristSendMsg < 3 {
		g.TouristSendMsg = uint8(touristSendMsg)
		fields = append(fields, "tourist_send_msg")
		signal.TouristSendMsg = &g.TouristSendMsg
	}
	if touristSendPic, err := strconv.ParseInt(c.PostForm("touristSendPic"), 10, 16); err == nil && touristSendPic > 0 && touristSendPic < 3 {
		g.TouristSendPic = uint8(touristSendPic)
		fields = append(fields, "tourist_send_pic")
		signal.TouristSendPic = &g.TouristSendPic
	}
	if isChangeFee, err := strconv.ParseInt(c.PostForm("isChangeFee"), 10, 16); err == nil && isChangeFee == 1 {
		if memberFee, err := strconv.ParseUint(c.PostForm("memberFee"), 10, 16); err == nil {
			g.MemberFee = memberFee
			fields = append(fields, "member_fee")
			signal.MemberFee = &g.MemberFee
		}
	}

	if themeId, err := strconv.ParseInt(c.PostForm("themeId"), 10, 16); err == nil {
		if themeId == 0 {
			g.ThemeId = int16(themeId)
			fields = append(fields, "theme_id")
			signal.ThemeId = &g.ThemeId
			var t uint8 = group_e.SETTING_CUSTOMIZED
			signal.ThemeType = &t
		} else if rows, err := res_m.GroupThemeGetAllInUse(model.Db); err == nil {
			for _, i := range rows {
				if i.ID == uint64(themeId) {
					g.ThemeId = int16(themeId)
					fields = append(fields, "theme_id")
					signal.ThemeId = &g.ThemeId
					signal.ThemeUrl = &i.Url
					var t uint8 = group_e.SETTING_OFFICIAL
					signal.ThemeType = &t
					break
				}
			}
		}
	}

	if len(welcomeText) > 0 {
		if len([]rune(welcomeText)) > group_e.GROUP_INTRODUCTION_LENGTH_LIMIT {
			model.Log.Warnf("ModifyGroupInfo %s - text too long", imGroupId)
		} else {
			gwt := group_m.GroupWelcomeText{GroupId: imGroupId, UserId: userId, Text: welcomeText}
			if err = gwt.Save(model.Db); err != nil {
				model.Log.Warnf("ModifyGroupInfo %s - Save WelcomeText FAILED:%v", imGroupId, err)
			}
		}
	}

	// 没必要就不调用
	if len(fields) > 0 {
		db := g.Update(model, imGroupId, fields)
		if db.Error != nil {
			return myContext, db.Error
		}

		buf, err := json.Marshal(signal)
		if err == nil {
			systemMsg := group_m.GroupSystemMsg{MsgId: group_e.GroupEditProfileSignal, Source: externalId, Content: string(buf)}
			signal_s.SendSignalMsg(model, imGroupId, systemMsg, false)
		}
	}

	if diceNum, err := strconv.Atoi(c.PostForm("diceNum")); err == nil {
		if diceNum <= 0 || diceNum > group_e.GROUP_DICE_NUM_MAX {
			model.Log.Warnf("ModifyGroupInfo %s: Invalid dice number %d", imGroupId, diceNum)
		} else {
			gs := group_m.GroupSetting{GroupId: imGroupId, DiceNum: uint16(diceNum)}
			if err = gs.SetDiceNum(model.Db); err != nil {
				model.Log.Warnf("ModifyGroupInfo %s: set failed: %s", imGroupId, err.Error())
			}
		}
	}
	if diceType, err := strconv.Atoi(c.PostForm("diceType")); err == nil {
		if diceType <= 0 || diceType > 2 {
			model.Log.Warnf("ModifyGroupInfo %s: Invalid dice diceType %d", imGroupId, diceType)
		} else {
			gs := group_m.GroupSetting{GroupId: imGroupId, DiceType: uint16(diceType)}
			if err = gs.SetDiceType(model.Db); err != nil {
				model.Log.Warnf("ModifyGroupInfo %s: set failed: %s", imGroupId, err.Error())
			}
		}
	}

	resp.ResponseOk(c, nil)
	return myContext, nil
}
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484

// @Tags 群组
// @Summary 搜索群
// @Accept application/x-www-form-urlencoded
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param code path string true "群CODE"
// @Success 200 {object} []group_cv.GroupInfo
// @Router /v1/imGroup/search/{code} [get]
func SearchGroup(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)

	myUserId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}

	code := c.Param("code")
	if len(code) <= 0 {
		return myContext, myerr.NewSysError("code 为必填项")
	}

	model := domain.CreateModelContext(myContext)

	result := make([]group_cv.GroupInfo, 0)
	total := 0

	g, err := group_m.GetGroupByCode(model, code)
	if err != nil {
		return myContext, err
	}

	if g != nil {
		owner, err := user_m.GetUser(model, g.Owner)
		if err != nil {
			return myContext, err
		}
		if owner.Status == user_e.UserStatusFrozen {
			if flag, _ := user_m.IsSuperManager(model, myUserId); !flag {
				// 被封锁的用户,除了超管账户,其它用户搜索他的群组和个人ID,搜索结果为空
				resp.ResponsePageOk(c, result, uint(total), 1)
				return myContext, nil
			}
		}
		supportLevels, err := group_s.NewGroupService(myContext).GetWeekMaxSupportLevelMap()
		if err != nil {
			return myContext, err
		}

		// 允许多个结果,虽然目前只有一个群
		groupIds := []string{g.ImGroupId}
		groupInfo := map[string]group_m.GroupInfo{g.ImGroupId: *g}

		if len(groupIds) > 0 {
			countryInfo, err := res_c.GetCountryIconMap(model)
			if err != nil {
				return myContext, err
			}

			for _, i := range groupIds {
				var password *string = nil
				if len(groupInfo[i].Password) > 0 && groupInfo[i].Owner != myUserId {
					emptyStr := ""
					password = &emptyStr
				}

				memberCount, err := group_m.GetMemberCount(model.Db, i)
				if err != nil {
					return myContext, err
				}

				result = append(result, group_cv.GroupInfo{
					GroupBasicInfo: group_cv.GroupBasicInfo{
						GroupId:      groupInfo[i].TxGroupId,
						Name:         groupInfo[i].Name,
						Introduction: groupInfo[i].Introduction,
						Notification: groupInfo[i].Notification,
						FaceUrl:      groupInfo[i].FaceUrl,
						//Owner_Account:   i.Owner_Account,
						MemberNum:    memberCount,
						Code:         groupInfo[i].Code,
						CountryIcon:  countryInfo[groupInfo[i].Country],
						Password:     password,
						SupportLevel: supportLevels[i],
						MicNumType:   int(groupInfo[i].MicNumType),
					},
				})
			}
		}
	}
	resp.ResponsePageOk(c, result, uint(total), 1)
	return myContext, nil
}

// @Tags 群组
// @Summary 离开群组(obsolete)
// @Accept application/x-www-form-urlencoded
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param groupId path string true "群ID"
// @Success 200 {object} uint
// @Router /v1/imGroup/member/{groupId} [delete]
func LeaveGroup(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)

	groupId := c.Param("groupId")
	if len(groupId) <= 0 {
		return myContext, myerr.NewSysError("groupId 为必填项")
	}

	userId, externalId, err := req.GetUserIdAndExtId(c, myContext)
	if err != nil {
		return myContext, err
	}

	model := domain.CreateModelContext(myContext)

	groupInfo, err := group_m.GetInfoByTxGroupId(model, groupId)
	if groupInfo == nil {
		return myContext, bizerr.GroupNotFound
	}

	if userId == groupInfo.Owner {
		return myContext, bizerr.OwnerCannotLeave
	}

	if err = group_s.NewGroupService(myContext).LeaveGroup(model, groupId, userId, externalId); err != nil {
		return myContext, err
	}

	resp.ResponseOk(c, nil)
	return myContext, nil
}

// @Tags 群组
// @Summary 成为永久成员
// @Accept application/x-www-form-urlencoded
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param groupId path string true "群ID"
// @Param isInvite formData int false "是否群邀请0否1是"
// @Success 200 {object} uint "结果:1 为新加入成功;2 为已经是群成员"
// @Router /v1/imGroup/permanent/{groupId} [put]
func AddPermanentMember(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)

	groupId := c.Param("groupId")
	if len(groupId) <= 0 {
		return myContext, myerr.NewSysError("groupId 为必填项")
	}
	isInvite, err := strconv.Atoi(c.PostForm("isInvite"))
	if err != nil {
		isInvite = 0
	}

	userId, externalId, _, nick, avatar, err := req.GetUserEx(c, myContext)
	if err != nil {
		return myContext, err
	}

	model := domain.CreateModelContext(myContext)

	ip := req.GetRequestIP(c)
	imei, err := req.GetAppImei(c)
	if err != nil {
		imei, err = user_m.GetUserImeiStr(model, userId)
		if err != nil {
			return myContext, err
		}
	}

	groupId, err = group_m.ToImGroupId(model, groupId)
	if err != nil {
		return myContext, err
	}

	// 群是否被封禁
	banned := group_m.GroupBanned{ImGroupId: groupId}
	if err = banned.Get(model); err != gorm.ErrRecordNotFound {
		return myContext, bizerr.GroupIsBanned
	}

	// 已经成员的,直接返回
	rec, err := group_m.GetJoinedGroups(model.Db, userId)
	if err != nil {
		return myContext, err
	}
	for _, i := range rec {
		if i.GroupId == groupId {
			resp.ResponseOk(c, group_e.ADD_GROUP_DUPLICATE)
			return myContext, nil

		}
	}

	// 用户是否在群的黑名单中
	if group_m.InGroupBlackList(model, groupId, imei, ip, userId) {
		return myContext, bizerr.InBlacklist
	}

	// 检查所在群数是不是已达上限
	maxJoin, err := group_s.NewGroupService(myContext).GetJoinGroupLimit(userId)
	if err != nil {
		return myContext, err
	}
	isVip, _, err := user_m.IsVip(userId)
	if err != nil {
		return myContext, err
	}
	if uint(len(rec)) >= maxJoin {
		if isVip {
			return myContext, bizerr.GroupLimitReached
		} else {
			return myContext, bizerr.GroupLimitReachedVip
		}
	}

	// 不在房间内的不能成为永久成员
	userIds, err := group_m.RoomLivingExistsUserId(groupId)
	if err != nil {
		return myContext, err
	}
	inRoom := false
	for _, u := range userIds {
		if u == userId {
			inRoom = true
			break
		}
	}
	if !inRoom {
		if !config.AppIsLocal() {
			return myContext, bizerr.IncorrectState
		}
	}
	// 加入群组是否需要收费
	needCost, err := AddPermanentMemberCost(c, myContext, isInvite, userId, groupId)
	if err != nil {
		return myContext, err
	}

	gm := group_m.GroupMember{
		GroupId: groupId,
		UserId:  userId,
	}
	if err = gm.Create(model.Db); err != nil {
		return myContext, err
	}

	// 新进群的公屏消息
	if nobleLevel, err := noble_m.GetNobleLevel(model.Db, userId); err == nil {
		msg := group_m.CommonPublicMsg{Type: group_e.UserJoinPublicScreenMsg,
			ExternalId: externalId, Nick: nick, Avatar: avatar, IsVip: isVip, NobleLevel: nobleLevel}
		buf, err := json.Marshal(msg)
		if err == nil {
			go func(groupId, text string) {
				defer func() {
					if r := recover(); r != nil {
						//打印错误堆栈信息
						mylogrus.MyLog.Errorf("SendCustomMsg SYSTEM ACTION PANIC: %v, stack: %v", r, string(debug.Stack()))
					}
				}()
				signal_s.SendCustomMsg(domain.CreateModelContext(model.MyContext), groupId, nil, text)
			}(groupId, string(buf))
		}
	}

	// fixme: 这些缓存还需要吗?
	group_c.ClearGroupMemberCount(groupId)
	group_c.AddGroupMember(model, groupId, externalId)

	if isInvite == 1 && !needCost { // 已经接受了进群邀请
		group_m.AcceptGroupInviteJoin(model, userId, groupId)
	}

	resp.ResponseOk(c, group_e.ADD_GROUP_DONE)
	return myContext, nil
}

// 成员永久会议,检查是否需要收费
func AddPermanentMemberCost(c *gin.Context, myContext *mycontext.MyContext, isInvite int, userId uint64, groupId string) (bool, error) {
	needCost := true
	// 加入群组是否需要收费
	var model = domain.CreateModelContext(myContext)
	info, err := group_m.GetByImGroupId(model, groupId)
	if err != nil {
		return needCost, err
	}
	if info.MemberFee > 0 { // 需要收费
		// 旧版本(2.32.0以下),提示升级
		_, major, minor, _, err := req.GetAppVersion(c)
		if err != nil {
			return needCost, err
		}
		if major <= 2 && minor < 32 {
			return needCost, bizerr.UpgradeRequired
		}
		// 验证是否邀请
		if isInvite == 1 {
			inviteInfo, err := group_m.GetGroupInviteJoin(model, userId, groupId)
			if err != nil {
				return needCost, err
			}
			if inviteInfo != nil && time.Now().Unix()-inviteInfo.CreatedTime.Unix() < 86400 { // 一天内的邀请才有效
				needCost = false
			}
		}

		if needCost { // 需要扣黄钻
			err = ChangeDiamondAccountDetail(myContext, diamond_e.JoinGroupCost, mysql.ID(info.Id), userId, mysql.Num(info.MemberFee))
			if err != nil {
				return needCost, err
			}
			// 给一半群主
			err = ChangeDiamondAccountDetail(myContext, diamond_e.JoinGroupAdd, mysql.ID(info.Id), info.Owner, mysql.Num(math.Floor(float64(info.MemberFee)/2)))
			if err != nil {
				return needCost, err
			}
		}
	}
	return needCost, nil
}

func ChangeDiamondAccountDetail(myContext *mycontext.MyContext, operateType diamond_e.OperateType, originId mysql.ID, userId mysql.ID, diamondNum mysql.Num) error {
	db := mysql.Db.Begin()
	model := domain.CreateModelContext(myContext)
	diamondAccount, err := diamond_m.GetDiamondAccountByUserId(model, userId)
	if err != nil {
		return err
	}
	diamondAccountDetail, err := diamondAccount.ChangeDiamondAccountDetail(operateType, originId, diamondNum)
	if err != nil {
		db.Rollback()
		return err
	}
	if err := diamondAccountDetail.PersistentNoInTransactional(); err != nil {
		db.Rollback()
		return err
	}
	db.Commit()
	return nil
}

// @Tags 群组
// @Summary 退出永久成员
// @Accept application/x-www-form-urlencoded
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param groupId path string true "群ID"
// @Success 200 {object} uint
// @Router /v1/imGroup/permanent/{groupId} [delete]
func RemovePermanentMember(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)

	groupId := c.Param("groupId")
	if len(groupId) <= 0 {
		return myContext, myerr.NewSysError("groupId 为必填项")
	}

	userId, externalId, err := req.GetUserIdAndExtId(c, myContext)
	if err != nil {
		return myContext, err
	}

	model := domain.CreateModelContext(myContext)

	groupInfo, err := group_m.GetInfoByTxGroupId(model, groupId)
	if err != nil {
		return myContext, err
	}
	if groupInfo == nil {
		return myContext, bizerr.GroupNotFound
	}
	groupId = groupInfo.ImGroupId

	if userId == groupInfo.Owner {
		return myContext, bizerr.OwnerCannotLeave
	}

	if err = group_s.NewGroupService(myContext).LeaveGroupMember(model, groupId, userId, externalId); err != nil {
		return myContext, err
	}

	resp.ResponseOk(c, nil)
	return myContext, nil
}

type GroupMembersRsp struct {
	Members []group_cv.MemberDetail `json:"members"`
	Online  uint                    `json:"online"` // 在线人数
	Total   uint                    `json:"total"`
}

// @Tags 群组
// @Summary 获取永久成员列表
// @Accept application/x-www-form-urlencoded
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param groupId path string true "群ID"
// @Param pageSize query int false "分页大小 默认:10" default(10)
// @Param pageIndex query int false "第几个分页,从1开始 默认:1" default(1)
// @Success 200 {object} GroupMembersRsp
// @Router /v1/imGroup/permanent/{groupId} [get]
func GetPermanentMember(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)

	groupId := c.Param("groupId")
	if len(groupId) <= 0 {
		return myContext, bizerr.ParaMissing
	}

	pageSize, err := strconv.Atoi(c.Query("pageSize"))
	if err != nil || pageSize <= 0 {
		pageSize = 10
	}
	pageIndex, err := strconv.Atoi(c.Query("pageIndex"))
	if err != nil || pageIndex <= 0 {
		pageIndex = 1
	}

	userId, _, err := req.GetUserIdAndExtId(c, myContext)
	if err != nil {
		return myContext, err
	}

	model := domain.CreateModelContext(myContext)

	groupId, err = group_m.ToImGroupId(model, groupId)
	if err != nil {
		return myContext, err
	}

	rows, err := group_m.GetMembers(model.Db, groupId)
	if err != nil {
		return myContext, err
	}
	userIds := make([]uint64, 0)
	for _, i := range rows {
		userIds = append(userIds, i.UserId)
	}
	users, err := user_m.GetUserMapByIds(model, userIds)
	if err != nil {
		return myContext, err
	}
	model.Log.Infof("GetGroupMembers %s: memberNum = %d, user size = %d", groupId, len(rows), len(userIds))

	result := GroupMembersRsp{Total: uint(len(rows))}

	beginPos := pageSize * (pageIndex - 1)
	if uint(beginPos) < result.Total {
		// 取在线状态
		extIds := make([]string, 0)
		for _, i := range users {
			extIds = append(extIds, i.ExternalId)
		}
		statusMap, err := tim_m.GetOnlineStatus(model, extIds)
		if err != nil {
			return myContext, err
		}

		result.Online = 0
		for _, v := range statusMap {
			if v == online_e.IM_STATUS_ON_LINE {
				result.Online++
			}
		}
		model.Log.Infof("GetGroupMembers %s: statusMap size = %d, onLine = %d", groupId, len(statusMap), result.Online)

		roles, _, err := group_m.GetRolesInGroup(model, groupId)
		if err != nil {
			return myContext, err
		}

		nobleLevels, err := noble_m.BatchGetNobleLevel(model.Db, userIds)
		if err != nil {
			return myContext, err
		}

		vips, err := user_m.BatchGetVips(userIds)
		if err != nil {
			return myContext, err
		}

		model.Log.Infof("GetGroupMembers %s, users %v, roles: %v, nobles: %v, vips: %v", groupId, userIds, roles, nobleLevels, vips)

		roomUsers, err := group_m.RoomLivingExistsUserId(groupId)
		if err != nil {
			return myContext, err
		}

		roomUserMap := utils.SliceToMapUInt64(roomUsers)
		//model.Log.Infof("GetGroupMembers %s, roomStatusMap %v", groupId, roomStatusMap)

		// 排序规则 :在房间的优先,其次是在线,再次看角色,最后看贵族
		sort.Slice(userIds, func(i, j int) bool {
			ui := userIds[i]
			uj := userIds[j]

			_, ok1 := roomUserMap[ui]
			_, ok2 := roomUserMap[uj]
			if ok1 && !ok2 {
				return true
			} else if ok1 == ok2 {
				ei := users[ui].ExternalId
				ej := users[uj].ExternalId
				if statusMap[ei] > statusMap[ej] {
					return true
				}
				if statusMap[ei] == statusMap[ej] {
					if roles[ui] > roles[uj] {
						return true
					}
					if roles[ui] == roles[uj] {
						// 贵族5>贵族4>贵族3>贵族2>VIP
						if nobleLevels[ui] > nobleLevels[uj] && nobleLevels[ui] >= 2 {
							return true
						}
						if nobleLevels[ui] == nobleLevels[uj] || nobleLevels[ui] < 2 && nobleLevels[uj] < 2 {
							if vips[ui] != nil {
								if vips[uj] == nil {
									return true
								} else {
									return users[ui].Code < users[uj].Code
								}
							} else if vips[uj] == nil {
								return users[ui].Code < users[uj].Code
							}
						}
					}
				}
			}
			return false
		})

		model.Log.Infof("GetGroupMembers %s, sorted users: %v", groupId, userIds)

		endPos := pageSize * pageIndex
		if endPos > len(userIds) {
			endPos = len(userIds)
		}

		userIds = userIds[beginPos:endPos]
		userExtends, err := user_cv.BatchGetUserExtend(model, userIds, userId)
		if err != nil {
			return myContext, err
		}

		for _, u := range userIds {
			inRoom := false
			if _, ok := roomUserMap[u]; ok {
				inRoom = true
			}
			result.Members = append(result.Members, group_cv.MemberDetail{
				CvUserExtend: userExtends[u],
				Role:         roles[u],
				OnlineStatus: statusMap[users[u].ExternalId],
				InRoom:       inRoom,
			})
		}
	}
	resp.ResponseOk(c, result)
	return myContext, nil
}

// @Tags 群组
// @Summary 全服广播群消息(运营用,慎用)
// @Accept application/x-www-form-urlencoded
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param contentType formData int true "消息类型:1 跳转url;2 跳转房间"
// @Param content formData string true "消息内容"
// @Param h5url formData string false "要转跳的url"
// @Param groupId formData string false "群ID"
// @Success 200 {object} uint
// @Router /v1/imGroup/allGroupMsg [put]
func SendTextMsg(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)

	userId, err := req.GetUserId(c)
	if err != nil {
		return myContext, err
	}

	if !user_m.IsSuperUser(userId) {
		return myContext, bizerr.NoPrivileges
	}

	contentType, err := strconv.Atoi(c.PostForm("contentType"))
	if err != nil {
		return myContext, bizerr.ParaMissing
	}
	content := c.PostForm("content")
	if len(content) <= 0 {
		return myContext, bizerr.ParaMissing
	}

	h5url := ""
	groupId := ""
	if contentType == 1 {
		h5url = c.PostForm("h5url")
		if len(h5url) == 0 {
			return myContext, bizerr.InvalidParameter
		}
	} else if contentType == 2 {
		groupId = c.PostForm("groupId")
		if len(groupId) == 0 {
			return myContext, bizerr.InvalidParameter
		}
	} else {
		return myContext, bizerr.InvalidParameter
	}

	model := domain.CreateModelContext(myContext)

	txGroupId := groupId
	groupId, err = group_m.ToImGroupId(model, groupId)
	if err != nil {
		return myContext, err
	}

	gsm := group_m.GroupCustomMsg{
		CommonPublicMsg: group_m.CommonPublicMsg{Type: group_e.JumpMessage},
		ContentType:     contentType,
		Content:         content,
		H5:              h5url,
		GroupId:         txGroupId,
	}
	buf, err := json.Marshal(gsm)
	var failedCount uint = 0
	if err == nil {
		groupIds, err := group_m.GetAllGroupIds(model.Db)
		if err != nil {
			return myContext, err
		}
		for i, g := range groupIds {
			seq, err := signal_s.SendCustomMsg(model, g, nil, string(buf))
			if err == nil {
				model.Log.Infof("Succeeded in sending GroupCustomMsg to group %s, seq = %d", g, seq)
			} else {
				model.Log.Infof("Failed in sending GroupCustomMsg to group %s", g)
				failedCount++
			}
			if i%100 == 0 {
				time.Sleep(time.Millisecond * 500)
			}
		}
	}
	resp.ResponseOk(c, failedCount)
	return myContext, nil
}