1.2.1 • Published 3 years ago

wecloud-webim-sdk v1.2.1

Weekly downloads
-
License
Apache-2.0
Repository
-
Last release
3 years ago

即时通讯 wecloud-im-sdk

提供的主要功能有 基本聊天功能、1v1 视频通话

即时通讯官网 : https://www.wecloud.cn/product/message.html

demo:https://imwebtest.wecloud.cn

安装与引用 SDK

  1. 通过 script 标签方式直接引入
<!-- 自动引入全局变量 WebIM -->
<script src="/dist/bundle.js"></script>
  1. 通过 npm 包管理工具
npm i wecloud-webim-sdk
// 安装完成后,在代码中引用
import WebIM from "wecloud-webim-sdk";
  1. 单人音视频中,为提高 webrtc 在不同浏览器上的兼容性,你可以自行引入 WebRTC 适配器(WebRTC adapter) https://webrtc.github.io/adapter/adapter-latest.js

初始化及连接

1. 创建实例

const conn = new WebIM( options )
// options 可配置选项
{
   apiURL: "https://imapitest.wecloud.cn",  //接口请求地址 | 必须
   wsURL: 'wss://imapitest.wecloud.cn/ws',  //websocket URL
   heartBeatWait: 15000,					//websocket心跳间隔时间
   reConnectNumMax: 3,						//websocket 最大重连次数
   reConnectTimeWait: 8000,					//websocket 重新连接等待时间
   sendMessageTimeout: 8000,				//websocket 发送消息超时时间
   videoConstraints:{
      height: 720,
      width: 1280
   },                             //video预设,分辨率等... 默认为true
   audioConstraints:{}            //audio预设,默认为true
}

2. 添加回调函数

//连接
conn.onClosed = function () {}; //连接关闭时
conn.onConnected = function () {}; // 连接成功时
conn.onError = function () {}; //连接错误时

//消息
conn.onTextMessage = function () {}; //接收到文本消息时
conn.onImageMessage = function () {}; //接收到图片消息时
conn.onAudioMessage = function () {}; //接收到语音消息时
conn.onVideoMessage = function () {}; //接收到视频文件消息时
conn.onFileMessage = function () {}; //接收到文件消息时
conn.onCustomMessage = function () {}; //接收到自定义消息时

conn.onMessageReceived = function () {}; // 对方已接收消息
conn.onMessageRead = function () {}; // 对方已读消息时
conn.onWithdrawMessage = function () {}; // 对方撤回读消息时
conn.onMessageDelete = function () {}; // 对方删除消息时

// 会话
conn.onClientJoinConversation = function () {}; // 有人加入会话时
conn.onClientQuitConversation = function () {}; // 有人退出会话时
conn.onAddConversation = function () {}; //有人邀请请并创建多人会话时
conn.onDisbandConversation = function () {}; //解散群时通知
conn.onConversationMuted = function () {}; //会话设置禁言时
conn.onConversationUnMuted = function () {}; //会话取消禁言时
conn.onClientRemovedFromConversation = function () {}; // 有人被移出会话时
conn.onConversationNameChange = function () {}; //会话名称改变时
conn.onUpdataRemarksName = function () {}; // 群成员修改备注时
conn.onFriendApplication = function () {}; // 接收到好友申请
conn.onFriendAgree = function () {}; // 好友同意申请

//webrtc 单人
conn.onLocalStream = function (stream) {}; //可以用本地媒体流时
conn.onRemoteStream = function (stream) {}; //可以使用远端媒体流时
conn.onCall = function () {}; // 接收到被人呼叫时
conn.onClientJoined = function () {}; //对方加入通话时
conn.onRefuseAnswer = function () {}; //对方拒绝通话邀请时
conn.onClientLeave = function () {}; //对方离开通话时

// 会议
conn.onMeetingInvite = function () {}; //会议邀请时
conn.onMeetingReject = function () {}; //成员拒绝加入会议
conn.onMeetingAgree = function () {}; // 成员同意加入会议
conn.onMeetingMemberLeave = function () {}; // 成员离开会议

3. 开始连接

  1. 通过 sign 登录连接
const option = {
  timestamp: "",
  clientId: "",
  appKey: "",
  sign: "",
  platform: 1, //平台: 1 web, 2 安卓, 3 ios, 4 pc-win, 5 pc-macOs, 需与生成sign时的值一致
};
//option的内容由客户服务端返回
conn.open(option).then((res) => {
  const { clientId, token, wsURL } = res;
  console.log(clientId, token, wsURL);
});
  1. 通过 token 连接
const option = {
  clientId: "",
  token: "",
  wsURL: "",
};
conn.open(option).then();

4. 关闭连接

conn.close();

消息

消息类型(type)

  • text / -1 (文本消息)
  • image / -2 (图片消息)
  • audio / -3 (语音消息)
  • video / -4 (视频消息)
  • file / -5 (文件消息)

发送消息

//生成本地消息id,发送成功后随接口返回,可用于更新本地数据
const reqId = conn.createRequestId()

// 构造消息
const msg = conn.createMessage({
	reqId: reqId,	//必须
	to: conversationId,		//发送目标的会话id
	type: 'file',	//消息类型	(可自定义,在onCustomMessage回调函数里接收)
  file: {			//文件数据
     url: URL.createObjectURL(file),
     name: file.name,
     type: file.type,
     size: file.size,
     fileInfo: JSON.stringify({
       height: parseInt(width),
       width: parseInt(height)
     })
    }
    ...
})

// 类似接口返回的数据格式
const localMessageData = msg.loacalData
console.log(localMessageData)

//修改发送数据
msg.text = "hello"
msg.file.url = 'https://'
//发送的数据
const sendMessageData = msg.sendData
conn.send(sendMessageData).then(()=>{})

1、发送文本消息

// 生成reqId  消息发送成功后会返回  自定义生成,请确保唯一
const reqId = conn.createRequestId();
// 构造消息
const msg = conn.createMessage({
  reqId: reqId,
  to: conversationId,
  type: "text",
  text: text,
});

const sendMessageData = msg.sendData

// 发送数据
conn.send(sendMessageData).then(() => {});

2.、发送图片消息

// 生成reqId  消息发送成功后会返回  自定义生成,请确保唯一
const reqId = conn.createRequestId();

const msg = conn.createMessage({
  reqId: reqId,
  to: conversationId,
  type: "image",
  file: {
    url: "https://",
    name: file.name,
    type: file.type,
    size: file.size,
    fileInfo: JSON.stringify({
      height: parseInt(width),
      width: parseInt(height),
    }),
  },
});

// 发送数据
conn.send(sendMessageData).then(() => {});

3、发送视频消息

const msg = conn.createMessage({
  reqId: conn.createRequestId(),
  to: conversationId,
  type: "video",
  file: {
    url: "fileURL",
    name: file.name,
    type: file.type,
    size: file.size,
    fileInfo: JSON.stringify({
      duration: parseInt(vid.duration), // long 类型
    }),
  },
});

// 发送数据
conn.send(sendMessageData).then(() => {});

4、发送文件消息

const msg = conn.createMessage({
  reqId: conn.createRequestId(),
  to: currentConversationId,
  type: "file",
  file: {
    url: "url",
    name: file.name,
    type: file.type,
    size: file.size,
  },
});

// 发送数据
conn.send(sendMessageData).then(() => {});

5、 发送自定义消息

const msg = conn.createMessage({
  reqId: conn.createRequestId(),
  to: currentConversationId,
  type: [自定义],
  ...
})

// 发送数据
conn.send(sendMessageData).then(()=>{})

接收消息

见 初始化及连接 >> 添加回调函数。

//接收到文本消息时
conn.onTextMessage = function (data) {
   console.log(data)
}
//接收到图片消息时
conn.onImageMessage = function (data) {
   console.log(data)
}
...

获取历史消息

const option = {
  conversationId: "", //会话id	| 必须
  pageIndex: 1, //页码
  msgIdStart: "", //起始消息id
  msgIdEnd: "", //结束消息id
  pageSize: 10, //消息条数
  keyword: "", //关键词
};
conn.getHistoryMsg(option).then();

获取离线消息

// 如果接收到消息没有设为已接收状态,将会在获取离线消息接口获取到
conn.getOfflineList().then();

设置消息状态为已读

1、根据消息 id 设置消息已读

/**
 * @param {array} msgIds  消息id集合
 * @returns
 */
conn.setMessageRead(msgIds).then();

2、根据会话设置消息已读

const options = {
  conversationId: "",
  msgIdEnd: "", //当前消息id之前的全部未读消息设置为已读,缺省 则是设置当前会话全部已读
};

conn.setMessageReadByConversation(options);

设置消息状态为已接收(&已读)

设置为已接收状态时,下次将不会出现在拉取离线消息的接口

/**
 * @param {array} msgIds  消息id集合
 * @param {boolean} readStatus  消息已读状态,默认为true 既设置消息状态为已读已接收
 * @returns
 */
conn.setMessageReceived(msgIds, readStatus).then();

消息撤回

/**
 * @param {array} msgIds  消息id集合
 * @returns
 */
conn.withdrawMessage(msgIds).then((res) => {
  console.log(res);
});

删除消息

/**
 * @param {array} msgIds  消息id集合
 * @returns
 */
conn.deleteMessages(msgIds).then((res) => {});

会话

创建会话

const options = {
    name:'name', 						//会话名称
    clientIds:['clientA','clientB'], 	//会话中包含的用户,
    attributes:{}						//自定义属性
}
conn.createConversation(options).then((res)=>{ console.log(res) })

获取会话列表

conn.getConversationList().then((res) => {
  console.log(res);
});

根据会话 id 获取会话信息

/**
 * @param {string} conversationId - 会话id
 * @returns
 */
conn.getConversationInfo(conversationId).then((res) => {});

获取会话成员

/**
 * @param {string} conversationId - 会话id
 * @param {object} filterOptions - 指定条件的成员 | 非必须
 * @returns
 */
const filterOptions = {
  roles: [], // 角色 1:普通成员 2:管理员 3:群主
  muted: 1, // 1-未禁言 2-禁言
  clientIds: [],
};
conn.getMembers(conversationId, filterOptions).then();

添加成员

/**
 * @param {string} conversationId - 会话id
 * @param {array} clientIds - 指定条件的成员 | 非必须
 * @returns
 */
conn.addMembers(conversationId, clientIds).then();

移除成员

/**
 * @param {string} conversationId - 会话id
 * @param {array} clientIds - 指定条件的成员 | 非必须
 * @returns
 */
conn.removeMembers(conversationId, clientIds);

退出会话

/**
 * @param {string} conversationId - 会话id
 * @returns
 */
conn.quitConversation(conversationId).then();

修改会话拓展字段

/**
 * @param {string} conversationId - 会话id
 * @param {*} attributes - 拓展字段
 * @returns
 */
conn.updataConversationAttrs(conversationId, attributes).then();

修改会话名称

/**
 * @param {string} conversationId - 会话id
 * @param {string} name - 会话名称
 * @returns
 */
conn.updataConversationName(conversationId, name).then();

修改会话中自己的昵称

/**
 * @param {string} conversationId - 会话id
 * @param {string} clientRemarkName - 昵称
 * @returns
 */
conn.updataRemarks(conversationId, clientRemarkName).then();

设置管理员

/**
 * @param {string} conversationId - 会话id
 * @param {array} clientIds
 * @param {boolean} status 	- 默认true:设置管理员,false:取消管理员
 * @returns
 */
conn.updataRemarks(conversationId, clientIds, status).then();

群主转让

/**
 * @param {string} conversationId - 会话id
 * @param {string} clientId
 * @returns
 */
conn.transferOwner(conversationId, clientId).then();

设置成员禁言状态

/**
 * @param {string} conversationId - 会话id
 * @param {array} clientIds
 * @param {boolean} status 	- true 禁言  false:取消禁言
 * @returns
 */
conn.setMemberMuted(conversationId, clientIds, status).then();

设置会话禁言状态

/**
 * @param {string} conversationId - 会话id
 * @param {boolean} status 	- true 禁言  false:取消禁言
 * @returns
 */
conn.setGroupMuted(conversationId, status).then();

解散会话

/**
 * @param {string} conversationId - 会话id
 * @returns
 */
conn.disbandConversation(conversationId).then();

设置会话状态(隐藏、显示) --- 暂时不用

status 为 false 下次将不会通过获取会话列表接口获取,会话、历史数据不会被删除

const conversationIds = ["clientA"]; //array, 会话id集合
const status = false; //bolean  true 显示, false隐藏
conn.setConversationStatus(conversationIds, status).then(() => {});

WebRTC 视频通话(1v1)

呼叫

获取到视频通话的 channelId, 对方也将收到视频通话邀请消息

const option = {
   toClient: "", 	      //呼叫方的clientId  | 必须
   type: 'video'  			//呼叫类型 voice/video  默认为video,
   conversationId: '',  	//会话id | 非必须
   push:'',					//接收方展示的系统推送内容
   pushCall: false 			//	是否需要给对方发系统通知
   attrs:{}  				//自定义数据 | 非必须
};
conn.call(option).then()

接收到视频通话邀请

conn.onCall = function (data) {}; // 接收到被人呼叫时

加入视频通话

const option = {
  //onCall回调会返回
  channelId: "4s53s2wews", //每次视频通话的房间id
  type: "video", // voice,video(默认)
};
conn.join(option).then();

本地、远端流媒体处理

见添加回调函数。示例:

<video autoplay playsinline class="remote-video"></video>
<!-- muted 本地播放不需要播放声音 -->
<video autoplay playsinline muted class="local-video"></video>

<script>
  // 加入当前音视频房间
  conn.join({ channelId, type });

  // 本地媒体流可用时
  conn.onLocalStream = (stream) => {
    document.querySelector(".local-video").srcObject = stream;
  };

  // 远程媒体流可用时
  conn.onRemoteStream = (stream) => {
    document.querySelector(".remote-video").srcObject = stream;
  };
</script>

挂断

conn.hangup().then(() => {});

关闭本地媒体

conn.closeLocalMedia();

开启、关闭本地录像

/**
 * @param {boolean} status false:关闭本地录制视频,true:开启本地录制视频
 * @returns
 */
conn.enableVideo(status);

开启、关闭麦克风

/**
 * @param {boolean} status false:关闭录音,true:开启录音
 * @returns
 */
conn.enableAudio(status);

切换摄像头

/**
 * @param {boolean} mode environment:后置摄像头 user:前置摄像头
 * @returns
 */
conn.switchCamera(mode);

设置视频参数

const options = {
  height: 400, //分辨率高
  width: 600, //分辨率宽
};
conn.applyVideoConstraints(options); //  (video constrains)
1.2.0

3 years ago

1.2.1

3 years ago

1.1.1

3 years ago

1.1.0

3 years ago

1.0.2

3 years ago