腾讯 IM即时通讯 Java简单封装工具

腾讯IM常量

TximConstants.class

/**
* @Desc 腾讯云IM接口与常量
* @auth Lizr

*/
public class TximConstant {

  /**
   * 应用 SDKAppID
   */
  public static final long SKD_APP_ID = -1;

  /**
   * 密钥
   */
  public static final String KEY = "";

  /**
   * 管理员ID
   */
  public static final String ADMIN_ID = "administrator";

  /**
   * UserSig 的有效期,单位为秒
   */
  public static final Long EXPIRE = 10L;

  /**
   * 导入单个帐号
   */
  public static final String ACCOUNT_IMPORT = "https://console.tim.qq.com/v4/im_open_login_svc/account_import";

  /**
   * 导入多个帐号
   */
  public static final String MULTIACCOUNT_IMPORT = "https://console.tim.qq.com/v4/im_open_login_svc/multiaccount_import";

  /**
   * 删除帐号
   */
  public static final String ACCOUNT_DELETE = "https://console.tim.qq.com/v4/im_open_login_svc/account_delete";

  /**
   * 查询帐号
   */
  public static final String ACCOUNT_CHECK = "https://console.tim.qq.com/v4/im_open_login_svc/account_check";

  /**
   * 获取群成员详细资料
   */
  public static final String GET_GROUP_MEMBER_INFO = "https://console.tim.qq.com/v4/group_open_http_svc/get_group_member_info";

  /**
   * 单发单聊消息
   */
  public static final String SENDMSG = "https://console.tim.qq.com/v4/openim/sendmsg";

  /**
   * 获取 App 中的所有群组
   */
  public static final String GET_APPID_GROUP_LIST = "https://console.tim.qq.com/v4/group_open_http_svc/get_appid_group_list";

  /**
   * 获取群详细资料
   */
  public static final String GET_GROUP_INFO = "https://console.tim.qq.com/v4/group_open_http_svc/get_group_info";

  /**
   * 创建群组
   */
  public static final String CREATE_GROUP = "https://console.tim.qq.com/v4/group_open_http_svc/create_group";

  /**
   * 修改群基础资料
   */
  public static final String MODIFY_GROUP_BASE_INFO = "https://console.tim.qq.com/v4/group_open_http_svc/modify_group_base_info";

  /**
   * 增加群成员
   */
  public static final String ADD_GROUP_MEMBER = "https://console.tim.qq.com/v4/group_open_http_svc/add_group_member";

  /**
   * 删除群成员
   */
  public static final String DELETE_GROUP_MEMBER = "https://console.tim.qq.com/v4/group_open_http_svc/delete_group_member";

  /**
   * 修改群成员资料
   */
  public static final String MODIFY_GROUP_MEMBER_INFO = "https://console.tim.qq.com/v4/group_open_http_svc/modify_group_member_info";

  /**
   * 解散群组
   */
  public static final String DESTROY_GROUP = "https://console.tim.qq.com/v4/group_open_http_svc/destroy_group";

  /**
   * 在群组中发送普通消息
   */
  public static final String SEND_GROUP_MSG = "https://console.tim.qq.com/v4/group_open_http_svc/send_group_msg";

  /**
   * 在群组中发送系统通知
   */
  public static final String SEND_GROUP_SYSTEM_NOTIFICATION = "https://console.tim.qq.com/v4/group_open_http_svc/send_group_system_notification";


}

工具类所需的im实体类

CommonQuery

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;

/**
 * 公共查询参数
 * @author Lizr
 */

@ApiModel(value = "通用分页参数")
@Data
public class CommonQuery implements Serializable {

    @ApiModelProperty(value = "页码", example = "1")
    private int pageIndex;

    @ApiModelProperty(value = "条数", example = "10")
    private int pageSize;

}

TximGroupMemberPageQuery

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * @author Lizr
 */
@Data
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "TximGroupMemberPageQuery对象", description = "聊天室成员列表查询参数")
public class TximGroupMemberPageQuery extends CommonQuery {

    @ApiModelProperty(value = "聊天室ID")
    private String groupId;
}

TximGroupPageQuery

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * @author Lizr
 */
@Data
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "TximGroupPageQuery对象", description = "聊天室列表查询参数")
public class TximGroupPageQuery extends CommonQuery {

    @ApiModelProperty(value = "名称关键字")
    private String name;
}

工具类

TximUtil.class

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.live.edu.entity.app.query.TximGroupMemberPageQuery;
import com.live.edu.entity.app.query.TximGroupPageQuery;
import lombok.Data;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.zip.Deflater;
/**
 * @Desc 腾讯 IM 工具
 * @auth Lizr
 */
@SuppressWarnings("all")
public class TximUtil {

    public static void main(String[] args) {
        System.out.println("测试UserSig");
        System.out.println(genUserSig("529"));
        // 导入账号到腾讯云im系统
        accountImport("520", "机器人520号");
        // 入群
        TximChatroomMember tximChatroomMember = new TximChatroomMember();
        tximChatroomMember.setGroupId("4");
        List<Member> memberList = new ArrayList<>();
        Member member = new Member();
        member.setId(529);
        member.setNiName("机器人5号");
        memberList.add(member);
        tximChatroomMember.setMemberList(memberList);
        addGroupMember(tximChatroomMember);
        System.out.println("================= 入群 =================\n");
        // 查看群成员
        TximGroupMemberPageQuery query = new TximGroupMemberPageQuery();
        query.setPageIndex(1);
        query.setPageSize(10);
        query.setGroupId("4");
        System.out.println("================= 获取群成员列表 =================\n" + JSONObject.toJSONString(getGroupMemberList(query)));
    }

    /**
     * 新增群聊
     */
    public static void createGroup(TximChatroom tximChatroom) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("GroupId", String.valueOf(tximChatroom.getId()));
        requestBody.put("Type", "ChatRoom");
        requestBody.put("Name", tximChatroom.getName());
        requestBody.put("Introduction", tximChatroom.getIntroduction());
        requestBody.put("Notification", tximChatroom.getNotice());
        requestBody.put("MaxMemberCount", tximChatroom.getNum());
        JSONObject json = TximUtil.requestPost(TximConstant.CREATE_GROUP, TximConstant.ADMIN_ID, requestBody);
        if (!"OK".equals(json.getString("ActionStatus"))) {
            throw new RRException("聊天室添加失败:" + json.toString());
        }
    }

    /**
     * 导入后台账号到聊天系统
     */
    public static Result<Void> accountImport(String userId, String nick) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("Identifier", userId);
        requestBody.put("Nick", nick);
        requestPost(TximConstant.ACCOUNT_IMPORT, TximConstant.ADMIN_ID, requestBody);
        return Result.success();
    }

    /**
     * 增加群成员
     */
    public static void addGroupMember(TximChatroomMember params) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("GroupId", params.getGroupId());
        JSONArray memberList = new JSONArray();
        for (Member member : params.getMemberList()) {
            JSONObject memberAccount = new JSONObject();
            memberAccount.put("Member_Account", String.valueOf(member.getId()));
            memberList.add(memberAccount);
        }
        requestBody.put("MemberList", memberList);
        // 是否静默删人。0表示非静默删人,1表示静默删人
        requestBody.put("Silence", 0);
        JSONObject json = requestPost(TximConstant.ADD_GROUP_MEMBER, TximConstant.ADMIN_ID, requestBody);
        if (!"OK".equals(json.getString("ActionStatus"))) {
            throw new RRException("增加群成员失败:" + json.toString());
        }
        // 添加成功后设置群名片
        for (Member member : params.getMemberList()) {
            updateNameCard(params.getGroupId(), String.valueOf(member.getId()), member.getNiName());
        }
    }

    /**
     * 删除群成员
     */
    public static void deleteGroupMember(TximChatroomMemberIds params) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("GroupId", params.getGroupId());
        JSONArray memberList = new JSONArray();
        for (String memberId : params.getMemberIds()) {
            memberList.add(memberId);
        }
        requestBody.put("MemberToDel_Account", memberList);
        // 是否静默删人。0表示非静默删人,1表示静默删人
        requestBody.put("Silence", 0);
        JSONObject json = requestPost(TximConstant.DELETE_GROUP_MEMBER, TximConstant.ADMIN_ID, requestBody);
        if (!"OK".equals(json.getString("ActionStatus"))) {
            throw new RRException("删除群成员失败:" + json.toString());
        }
    }

    /**
     * 设置/取消 管理员
     */
    public static void updateAdmin(String groupId, String memberId, boolean isAdmin) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("GroupId", groupId);
        requestBody.put("Member_Account", memberId);
        requestBody.put("Role", isAdmin ? "Admin" : "Member");
        JSONObject json = requestPost(TximConstant.MODIFY_GROUP_MEMBER_INFO, TximConstant.ADMIN_ID, requestBody);
        if (!"OK".equals(json.getString("ActionStatus"))) {
            throw new RRException("修改管理员失败:" + json.toString());
        }
    }

    /**
     * 设置群成员名片
     */
    public static void updateNameCard(String groupId, String memberId, String nameCard) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("GroupId", groupId);
        requestBody.put("Member_Account", memberId);
        requestBody.put("NameCard", nameCard);
        JSONObject json = requestPost(TximConstant.MODIFY_GROUP_MEMBER_INFO, TximConstant.ADMIN_ID, requestBody);
        if (!"OK".equals(json.getString("ActionStatus"))) {
            throw new RRException("设置群成员名片失败:" + json.toString());
        }
    }

    /**
     * 修改群名称
     */
    public static void updateGroupName(String groupId, String groupName) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("GroupId", groupId);
        requestBody.put("Name", groupName);
        JSONObject json = requestPost(TximConstant.MODIFY_GROUP_BASE_INFO, TximConstant.ADMIN_ID, requestBody);
        if (!"OK".equals(json.getString("ActionStatus"))) {
            throw new RRException("修改群名称失败:" + json.toString());
        }
    }

    /**
     * 修改群公告
     */
    public static void updateGroupNotification(String groupId, String notification) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("GroupId", groupId);
        requestBody.put("Notification", notification);
        JSONObject json = requestPost(TximConstant.MODIFY_GROUP_BASE_INFO, TximConstant.ADMIN_ID, requestBody);
        if (!"OK".equals(json.getString("ActionStatus"))) {
            throw new RRException("修改群公告失败:" + json.toString());
        }
    }

    /**
     * 解散群
     */
    public static void destroyGroup(String groupId) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("GroupId", groupId);
        JSONObject json = TximUtil.requestPost(TximConstant.DESTROY_GROUP, TximConstant.ADMIN_ID, requestBody);
        if (!"OK".equals(json.getString("ActionStatus"))) {
            throw new RRException("解散群失败:" + json.toString());
        }
    }

    /**
     * 发送消息
     */
    public static void sendMsg(TximMsg tximMsg) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("SyncOtherMachine", 1);
        requestBody.put("From_Account", tximMsg.getFromMemberId());
        requestBody.put("To_Account", tximMsg.getToMemberId());
        requestBody.put("MsgRandom", new Random().nextInt());
        JSONArray msgBody = new JSONArray();
        JSONObject msgType = new JSONObject();
        msgType.put("MsgType", "TIMTextElem");
        msgBody.add(msgType);
        JSONObject msgContent = new JSONObject();
        JSONObject text = new JSONObject();
        text.put("Text", tximMsg.getMsg());
        msgType.put("MsgContent", text);
        msgBody.add(msgContent);
        requestBody.put("MsgBody", msgBody);
        JSONObject json = TximUtil.requestPost(TximConstant.SENDMSG, TximConstant.ADMIN_ID, requestBody);
        if (!"OK".equals(json.getString("ActionStatus"))) {
            throw new RRException("发送消息失败:" + json.toString());
        }
    }

    /**
     * 群里发送消息
     */
    public static void sendGroupMsg(TximGroupMsg tximGroupMsg) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("GroupId", tximGroupMsg.getGroupId());
        requestBody.put("From_Account", tximGroupMsg.getMemberId());
        requestBody.put("Random", new Random().nextInt());
        JSONArray msgBody = new JSONArray();
        JSONObject msgText = new JSONObject();
        msgText.put("MsgType", "TIMTextElem");
        JSONObject msgContent = new JSONObject();
        msgContent.put("Text", tximGroupMsg.getMsg());
        msgText.put("MsgContent", msgContent);
        msgBody.add(msgText);
        requestBody.put("MsgBody", msgBody);
        JSONObject json = TximUtil.requestPost(TximConstant.SEND_GROUP_MSG, TximConstant.ADMIN_ID, requestBody);
        if (!"OK".equals(json.getString("ActionStatus"))) {
            throw new RRException("发送消息失败:" + json.toString());
        }
    }

    /**
     * 查询群列表
     *
     * @param name - 群名模糊查询
     * @return Result -群列表
     */
    public static Result<Page<TximChatroom>> getGroupList(TximGroupPageQuery query) {
        int currPage = query.getPageIndex();
        int pageSize = query.getPageSize();
        String name = query.getName();
        List<TximChatroom> list = new ArrayList<>();
        JSONObject groupListJson = TximUtil.requestPost(TximConstant.GET_APPID_GROUP_LIST, TximConstant.ADMIN_ID, new JSONObject());
        if (isResultOk(groupListJson)) {
            Integer total = groupListJson.getInteger("TotalCount");
            if (total > 0) {
                // 群组详细信息请求包ids
                JSONArray requestGroupIdList = new JSONArray();
                // 查看全部群id
                JSONArray groupIdList = groupListJson.getJSONArray("GroupIdList");
                for (Object obj : groupIdList) {
                    requestGroupIdList.add(JSONObject.parseObject(obj.toString()).getString("GroupId"));
                }
                // 根据查询出来的id.查询指定群详情
                JSONObject requestBody = new JSONObject();
                requestBody.put("GroupIdList", requestGroupIdList);
                JSONObject result = TximUtil.requestPost(TximConstant.GET_GROUP_INFO, TximConstant.ADMIN_ID, requestBody);
                if (isResultOk(result)) {
                    // 查询群详情列表的结果
                    JSONArray groupInfos = result.getJSONArray("GroupInfo");
                    for (Object obj : groupInfos) {
                        JSONObject groupInfo = JSONObject.parseObject(obj.toString());
                        String chatRoomName = groupInfo.getString("Name");
                        // key关键字过滤
                        if (StringUtils.isNotBlank(name) && !chatRoomName.contains(name)) {
                            continue;
                        }
                        TximChatroom tximChatroom = new TximChatroom();
                        tximChatroom.setId(groupInfo.getString("GroupId"));
                        tximChatroom.setName(chatRoomName);
                        tximChatroom.setIntroduction(groupInfo.getString("Introduction"));
                        tximChatroom.setNotice(groupInfo.getString("Notification"));
                        tximChatroom.setNum(groupInfo.getInteger("MaxMemberNum"));
                        LocalDateTime createdTime = LocalDateTime.ofEpochSecond(groupInfo.getLong("CreateTime"), 0, ZoneOffset.ofHours(8));
                        tximChatroom.setCreatedTime(createdTime);
                        list.add(tximChatroom);
                    }
                }
            }
        }
        PageUtils page = new PageUtils(PageUtils.getPageList(list, currPage, pageSize), list.size(), pageSize, currPage);
        return Result.success(page);
    }

    /**
     * 查询群成员列表
     *
     * @param name - 群成员名模糊查询
     * @return Result -群列表
     */
    public static Result<Page<TximChatroomMemberList>> getGroupMemberList(TximGroupMemberPageQuery query) {
        int currPage = query.getPageIndex();
        int pageSize = query.getPageSize();
        List<TximChatroomMemberList> list = new ArrayList<>();
        JSONObject requestBody = new JSONObject();
        requestBody.put("GroupId", query.getGroupId());
        requestBody.put("Limit", query.getPageSize());
        requestBody.put("Offset", (query.getPageIndex() - 1) * query.getPageSize());
        JSONObject groupListJson = TximUtil.requestPost(TximConstant.GET_GROUP_MEMBER_INFO, TximConstant.ADMIN_ID, requestBody);
        if (isResultOk(groupListJson)) {
            JSONArray memberList = groupListJson.getJSONArray("MemberList");
            for (Object obj : memberList) {
                JSONObject member = JSONObject.parseObject(obj.toString());
                TximChatroomMemberList tximChatroomMemberList = new TximChatroomMemberList();
                tximChatroomMemberList.setId(member.getString("Member_Account"));
                tximChatroomMemberList.setName(member.getString("NameCard"));
                tximChatroomMemberList.setRole(member.getString("Role"));
                LocalDateTime createdTime = LocalDateTime.ofEpochSecond(member.getLong("JoinTime"), 0, ZoneOffset.ofHours(8));
                tximChatroomMemberList.setCreatedTime(createdTime);
                list.add(tximChatroomMemberList);
            }
        }
        PageUtils page = new PageUtils(PageUtils.getPageList(list, currPage, pageSize), list.size(), pageSize, currPage);
        return Result.success(page);
    }

    /**
     * 发送请求
     * @param requestBody{
     * sdkappid	App 在即时通信 IM 控制台获取的应用标识	在申请接入时获得
     *  identifier	用户名,调用 REST API 时必须为 App 管理员帐号	参见 App 管理员
     *  usersig	用户名对应的密码	参见 生成 UserSig
     *  random	标识当前请求的随机数参数	32位无符号整数随机数,取值范围0 - 4294967295
     *  contenttype	请求格式	固定值为json
     *  }
     * @param url
     * @param userId
     * @param requestBody
     * @return
     */
    public static JSONObject requestPost(String url, String userId, JSONObject requestBody) {
        try {
            System.out.println("================= requestPost =================");
            System.out.println("requestBody: " + requestBody.toString());
            StringBuilder requestUrl = new StringBuilder();
            requestUrl.append(url)
                    .append("?sdkappid=").append(TximConstant.SKD_APP_ID)
                    .append("&identifier=").append(userId)
                    .append("&usersig=").append(URLEncoder.encode(genUserSig(userId), "utf-8"))
                    .append("&random=").append(new Random().nextInt())
                    .append("&contenttype=").append("json");
            OkHttpClient client = new OkHttpClient();
            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=UTF-8"), requestBody.toJSONString());
            Request request = new Request.Builder().url(requestUrl.toString())
                    .header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8").post(body).build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            if (response.code() != 200) {
                return new JSONObject();
            }
            System.out.println(JSONObject.parseObject(result) + "\n");
            return JSONObject.parseObject(result);
        } catch (Exception e) {
            return new JSONObject();
        }
    }

    private static boolean isResultOk(JSONObject result) {
        return result != null && "OK".equals(result.getString("ActionStatus"));
    }

    /**
     * 【功能说明】用于签发 TRTC 和 IM 服务中必须要使用的 UserSig 鉴权票据
     * <p>
     * 【参数说明】
     *
     * @param userid - 用户id,限制长度为32字节,只允许包含大小写英文字母(a-zA-Z)、数字(0-9)及下划线和连词符。
     * @return usersig -生成的签名
     */
    public static String genUserSig(String userid) {
        return genUserSig(userid, TximConstant.EXPIRE, null);
    }

    /**
     * 【功能说明】用于签发 TRTC 和 IM 服务中必须要使用的 UserSig 鉴权票据
     * <p>
     * 【参数说明】
     *
     * @param userid - 用户id,限制长度为32字节,只允许包含大小写英文字母(a-zA-Z)、数字(0-9)及下划线和连词符。
     * @param expire - UserSig 票据的过期时间,单位是秒,比如 86400 代表生成的 UserSig 票据在一天后就无法再使用了。
     * @return usersig -生成的签名
     */
    public static String genUserSig(String userid, long expire) {
        return genUserSig(userid, expire, null);
    }

    /**
     * 【功能说明】
     * 用于签发 TRTC 进房参数中可选的 PrivateMapKey 权限票据。
     * PrivateMapKey 需要跟 UserSig 一起使用,但 PrivateMapKey 比 UserSig 有更强的权限控制能力:
     * - UserSig 只能控制某个 UserID 有无使用 TRTC 服务的权限,只要 UserSig 正确,其对应的 UserID 可以进出任意房间。
     * - PrivateMapKey 则是将 UserID 的权限控制的更加严格,包括能不能进入某个房间,能不能在该房间里上行音视频等等。
     * 如果要开启 PrivateMapKey 严格权限位校验,需要在【实时音视频控制台】/【应用管理】/【应用信息】中打开“启动权限密钥”开关。
     * <p>
     * 【参数说明】
     *
     * @param userid       - 用户id,限制长度为32字节,只允许包含大小写英文字母(a-zA-Z)、数字(0-9)及下划线和连词符。
     * @param expire       - PrivateMapKey 票据的过期时间,单位是秒,比如 86400 生成的 PrivateMapKey 票据在一天后就无法再使用了。
     * @param roomid       - 房间号,用于指定该 userid 可以进入的房间号
     * @param privilegeMap - 权限位,使用了一个字节中的 8 个比特位,分别代表八个具体的功能权限开关:
     *                     - 第 1 位:0000 0001 = 1,创建房间的权限
     *                     - 第 2 位:0000 0010 = 2,加入房间的权限
     *                     - 第 3 位:0000 0100 = 4,发送语音的权限
     *                     - 第 4 位:0000 1000 = 8,接收语音的权限
     *                     - 第 5 位:0001 0000 = 16,发送视频的权限
     *                     - 第 6 位:0010 0000 = 32,接收视频的权限
     *                     - 第 7 位:0100 0000 = 64,发送辅路(也就是屏幕分享)视频的权限
     *                     - 第 8 位:1000 0000 = 200,接收辅路(也就是屏幕分享)视频的权限
     *                     - privilegeMap == 1111 1111 == 255 代表该 userid 在该 roomid 房间内的所有功能权限。
     *                     - privilegeMap == 0010 1010 == 42  代表该 userid 拥有加入房间和接收音视频数据的权限,但不具备其他权限。
     * @return usersig - 生成带userbuf的签名
     */
    public static String genPrivateMapKey(String userid, long expire, long roomid, long privilegeMap) {
        byte[] userbuf = genUserBuf(userid, roomid, expire, privilegeMap, 0, "");  //生成userbuf
        return genUserSig(userid, expire, userbuf);
    }

    /**
     * 【功能说明】
     * 用于签发 TRTC 进房参数中可选的 PrivateMapKey 权限票据。
     * PrivateMapKey 需要跟 UserSig 一起使用,但 PrivateMapKey 比 UserSig 有更强的权限控制能力:
     * - UserSig 只能控制某个 UserID 有无使用 TRTC 服务的权限,只要 UserSig 正确,其对应的 UserID 可以进出任意房间。
     * - PrivateMapKey 则是将 UserID 的权限控制的更加严格,包括能不能进入某个房间,能不能在该房间里上行音视频等等。
     * 如果要开启 PrivateMapKey 严格权限位校验,需要在【实时音视频控制台】/【应用管理】/【应用信息】中打开“启动权限密钥”开关。
     * <p>
     * 【参数说明】
     *
     * @param userid       - 用户id,限制长度为32字节,只允许包含大小写英文字母(a-zA-Z)、数字(0-9)及下划线和连词符。
     * @param expire       - PrivateMapKey 票据的过期时间,单位是秒,比如 86400 生成的 PrivateMapKey 票据在一天后就无法再使用了。
     * @param roomstr      - 字符串房间号,用于指定该 userid 可以进入的房间号
     * @param privilegeMap - 权限位,使用了一个字节中的 8 个比特位,分别代表八个具体的功能权限开关:
     *                     - 第 1 位:0000 0001 = 1,创建房间的权限
     *                     - 第 2 位:0000 0010 = 2,加入房间的权限
     *                     - 第 3 位:0000 0100 = 4,发送语音的权限
     *                     - 第 4 位:0000 1000 = 8,接收语音的权限
     *                     - 第 5 位:0001 0000 = 16,发送视频的权限
     *                     - 第 6 位:0010 0000 = 32,接收视频的权限
     *                     - 第 7 位:0100 0000 = 64,发送辅路(也就是屏幕分享)视频的权限
     *                     - 第 8 位:1000 0000 = 200,接收辅路(也就是屏幕分享)视频的权限
     *                     - privilegeMap == 1111 1111 == 255 代表该 userid 在该 roomid 房间内的所有功能权限。
     *                     - privilegeMap == 0010 1010 == 42  代表该 userid 拥有加入房间和接收音视频数据的权限,但不具备其他权限。
     * @return usersig - 生成带userbuf的签名
     */
    public static String genPrivateMapKeyWithStringRoomID(String userid, long expire, String roomstr, long privilegeMap) {
        byte[] userbuf = genUserBuf(userid, 0, expire, privilegeMap, 0, roomstr);  //生成userbuf
        return genUserSig(userid, expire, userbuf);
    }

    private static String hmacsha256(String identifier, long currTime, long expire, String base64Userbuf) {
        String contentToBeSigned = "TLS.identifier:" + identifier + "\n"
                + "TLS.sdkappid:" + TximConstant.SKD_APP_ID + "\n"
                + "TLS.time:" + currTime + "\n"
                + "TLS.expire:" + expire + "\n";
        if (null != base64Userbuf) {
            contentToBeSigned += "TLS.userbuf:" + base64Userbuf + "\n";
        }
        try {
            byte[] byteKey = TximConstant.KEY.getBytes(StandardCharsets.UTF_8);
            Mac hmac = Mac.getInstance("HmacSHA256");
            SecretKeySpec keySpec = new SecretKeySpec(byteKey, "HmacSHA256");
            hmac.init(keySpec);
            byte[] byteSig = hmac.doFinal(contentToBeSigned.getBytes(StandardCharsets.UTF_8));
            return (Base64.getEncoder().encodeToString(byteSig)).replaceAll("\\s*", "");
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            return "";
        }
    }

    private static String genUserSig(String userid, long expire, byte[] userbuf) {

        long currTime = System.currentTimeMillis() / 1000;

        JSONObject sigDoc = new JSONObject();
        sigDoc.put("TLS.ver", "2.0");
        sigDoc.put("TLS.identifier", userid);
        sigDoc.put("TLS.sdkappid", TximConstant.SKD_APP_ID);
        sigDoc.put("TLS.expire", expire);
        sigDoc.put("TLS.time", currTime);

        String base64UserBuf = null;
        if (null != userbuf) {
            base64UserBuf = Base64.getEncoder().encodeToString(userbuf).replaceAll("\\s*", "");
            sigDoc.put("TLS.userbuf", base64UserBuf);
        }
        String sig = hmacsha256(userid, currTime, expire, base64UserBuf);
        if (sig.length() == 0) {
            return "";
        }
        sigDoc.put("TLS.sig", sig);
        Deflater compressor = new Deflater();
        compressor.setInput(sigDoc.toString().getBytes(StandardCharsets.UTF_8));
        compressor.finish();
        byte[] compressedBytes = new byte[2048];
        int compressedBytesLength = compressor.deflate(compressedBytes);
        compressor.end();
        return (new String(base64EncodeUrl(Arrays.copyOfRange(compressedBytes,
                0, compressedBytesLength)))).replaceAll("\\s*", "");
    }

    public static byte[] genUserBuf(String account, long dwAuthID, long dwExpTime,
                                    long dwPrivilegeMap, long dwAccountType, String RoomStr) {
        //视频校验位需要用到的字段,按照网络字节序放入buf中
        /*
         cVer    unsigned char/1 版本号,填0
         wAccountLen unsigned short /2   第三方自己的帐号长度
         account wAccountLen 第三方自己的帐号字符
         dwSdkAppid  unsigned int/4  sdkappid
         dwAuthID    unsigned int/4  群组号码
         dwExpTime   unsigned int/4  过期时间 ,直接使用填入的值
         dwPrivilegeMap  unsigned int/4  权限位,主播0xff,观众0xab
         dwAccountType   unsigned int/4  第三方帐号类型
         */
        int accountLength = account.length();
        int roomStrLength = RoomStr.length();
        int offset = 0;
        int bufLength = 1 + 2 + accountLength + 20;
        if (roomStrLength > 0) {
            bufLength = bufLength + 2 + roomStrLength;
        }
        byte[] userbuf = new byte[bufLength];

        //cVer
        if (roomStrLength > 0) {
            userbuf[offset++] = 1;
        } else {
            userbuf[offset++] = 0;
        }

        //wAccountLen
        userbuf[offset++] = (byte) ((accountLength & 0xFF00) >> 8);
        userbuf[offset++] = (byte) (accountLength & 0x00FF);

        //account
        for (; offset < 3 + accountLength; ++offset) {
            userbuf[offset] = (byte) account.charAt(offset - 3);
        }

        //dwSdkAppid
        userbuf[offset++] = (byte) ((TximConstant.SKD_APP_ID & 0xFF000000) >> 24);
        userbuf[offset++] = (byte) ((TximConstant.SKD_APP_ID & 0x00FF0000) >> 16);
        userbuf[offset++] = (byte) ((TximConstant.SKD_APP_ID & 0x0000FF00) >> 8);
        userbuf[offset++] = (byte) (TximConstant.SKD_APP_ID & 0x000000FF);

        //dwAuthId,房间号
        userbuf[offset++] = (byte) ((dwAuthID & 0xFF000000) >> 24);
        userbuf[offset++] = (byte) ((dwAuthID & 0x00FF0000) >> 16);
        userbuf[offset++] = (byte) ((dwAuthID & 0x0000FF00) >> 8);
        userbuf[offset++] = (byte) (dwAuthID & 0x000000FF);

        //expire,过期时间,当前时间 + 有效期(单位:秒)
        long currTime = System.currentTimeMillis() / 1000;
        long expire = currTime + dwExpTime;
        userbuf[offset++] = (byte) ((expire & 0xFF000000) >> 24);
        userbuf[offset++] = (byte) ((expire & 0x00FF0000) >> 16);
        userbuf[offset++] = (byte) ((expire & 0x0000FF00) >> 8);
        userbuf[offset++] = (byte) (expire & 0x000000FF);

        //dwPrivilegeMap,权限位
        userbuf[offset++] = (byte) ((dwPrivilegeMap & 0xFF000000) >> 24);
        userbuf[offset++] = (byte) ((dwPrivilegeMap & 0x00FF0000) >> 16);
        userbuf[offset++] = (byte) ((dwPrivilegeMap & 0x0000FF00) >> 8);
        userbuf[offset++] = (byte) (dwPrivilegeMap & 0x000000FF);

        //dwAccountType,账户类型
        userbuf[offset++] = (byte) ((dwAccountType & 0xFF000000) >> 24);
        userbuf[offset++] = (byte) ((dwAccountType & 0x00FF0000) >> 16);
        userbuf[offset++] = (byte) ((dwAccountType & 0x0000FF00) >> 8);
        userbuf[offset++] = (byte) (dwAccountType & 0x000000FF);


        if (roomStrLength > 0) {
            //roomStrLen
            userbuf[offset++] = (byte) ((roomStrLength & 0xFF00) >> 8);
            userbuf[offset++] = (byte) (roomStrLength & 0x00FF);

            //roomStr
            for (; offset < bufLength; ++offset) {
                userbuf[offset] = (byte) RoomStr.charAt(offset - (bufLength - roomStrLength));
            }
        }
        return userbuf;
    }

    private static byte[] base64EncodeUrl(byte[] input) {
        byte[] base64 = Base64.getEncoder().encode(input);
        for (int i = 0; i < base64.length; ++i)
            switch (base64[i]) {
                case '+':
                    base64[i] = '*';
                    break;
                case '/':
                    base64[i] = '-';
                    break;
                case '=':
                    base64[i] = '_';
                    break;
                default:
                    break;
            }
        return base64;
    }

    /**
     * 腾讯云IM聊天室
     */
    @Data
    public static class TximChatroom {

        /**
         * id
         */
        private String id;

        /**
         * 名称
         */
        private String name;

        /**
         * 说明
         */
        private String introduction;

        /**
         * 群公告
         */
        private String notice;

        /**
         * 群组人数
         */
        private Integer num;

        /**
         * 创建时间
         */
        private LocalDateTime createdTime;

    }

    /**
     * 腾讯云IM聊天室成员列表
     */
    @Data
    public static class TximChatroomMemberList {

        /**
         * id
         */
        private String id;

        /**
         * 名称
         */
        private String name;

        /**
         * 角色
         */
        private String role;

        /**
         * 创建时间
         */
        private LocalDateTime createdTime;

    }

    /**
     * 腾讯云IM聊天室成员
     */
    @Data
    public static class TximChatroomMember {

        /**
         * 聊天室ID
         */
        private String groupId;

        /**
         * 用户ID列表
         */
        private List<Member> memberList;

    }

    /**
     * 腾讯云IM聊天室成员
     */
    @Data
    public static class TximChatroomMemberIds {

        /**
         * 聊天室ID
         */
        private String groupId;

        /**
         * 用户ID列表
         */
        private List<String> memberIds;

    }

    /**
     * 腾讯云IM信息
     */
    @Data
    public static class TximMsg {

        /**
         * 发送人ID
         */
        private String fromMemberId;

        /**
         * 接收人ID
         */
        private String toMemberId;

        /**
         * 消息内容
         */
        private String msg;

    }

    /**
     * 腾讯云IM群信息
     */
    @Data
    public static class TximGroupMsg {

        /**
         * 群ID
         */
        private String groupId;

        /**
         * 发送人ID
         */
        private String memberId;

        /**
         * 消息内容
         */
        private String msg;

    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值