123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463 |
- var TIM = require('./tim-wx.js');
- var config = require('@/static/config.js');
- import requestConfig from '@/static/lib/requestConfig.js';
- var app, tim;
- var SDKConfig = {
- sdkappid: config.sdkAppID,
- accountType: config.accType,
- accountMode: 0 //帐号模式,0-表示独立模式,1-表示托管模式
- };
- var event = {
- onIMReady: function() {
- },
- onGetPusherList: function() {}, // 初始化成员列表
- onPusherJoin: function() {}, // 进房通知
- onPusherQuit: function() {}, // 退房通知
- onRoomClose: function() {}, // 群解散通知
- onRecvRoomTextMsg: function() {}, // 消息通知
- onMsgNotify: function() {}, // 监听新消息(私聊(包括普通消息和全员推送消息),普通群(非直播聊天室)消息)事件,必填
- onDestoryGroupNotify: function() {}, //群被解散(全员接收) 5
- onCustomGroupNotify: function() {}, //用户自定义通知(默认全员接收) 255
- onLoginSuccess: function() {}, //IM 登录成功的回调
- onBigGroupMsgNotify: function() {}, //监听新消息(大群)事件
- };
- function handleUnreadMsg(msg) {
- console.log('处理全局未读消息')
- if (msg.from === app.globalData.single.id + '_' + config.brandId + '_1') {
- return false
- }
- var adviserHouseId = msg.from.split("_")[1];
- if (!adviserHouseId) {
- return
- }
- var unReadMsgs = uni.getStorageSync('unReadMsgs') || {};
- var currentHouseUnReadMsgs = unReadMsgs[adviserHouseId] || {};//项目下消息数目
- unReadMsgs.total = unReadMsgs.total ? unReadMsgs.total : 0;
- currentHouseUnReadMsgs.total = currentHouseUnReadMsgs.total ? currentHouseUnReadMsgs.total : 0;
- unReadMsgs['total']++;
- currentHouseUnReadMsgs['total']++;
- let list = getCurrentPages();
- if (!currentHouseUnReadMsgs[msg.from]) {//项目未读消息下 对应 具体的顾问
- currentHouseUnReadMsgs[msg.from] = 1;
- } else {
- currentHouseUnReadMsgs[msg.from]++;
- console.log(unReadMsgs[msg.from], '今天你增加了吗')
- }
- console.log('未读计数增加', list)
- unReadMsgs[adviserHouseId] = currentHouseUnReadMsgs
- uni.setStorageSync('unReadMsgs', unReadMsgs)
- list.forEach((item, index) => {
- console.log(item, 'bpbpbpbpbp')
- if (item.$vm && item.$vm.refreshNumber && typeof item.$vm.refreshNumber === 'function') {
- console.log('户型图集增加', unReadMsgs)
- item.$vm.refreshNumber()
- }
- })
- console.log('全局未读消息处理完毕')
- }
- function msgReceived(msg) {
- // 实例化 对象
- var myMsg = JSON.parse(JSON.stringify(msg));
- console.log('接收到最新消息', myMsg)
- console.log('接收到最新消息', myMsg.data[0].payload)
- if (myMsg.data instanceof Array) {
- myMsg.data.forEach((item, index) => {
- console.log(item.conversationType)
- if (item.conversationType == 'GROUP') {
- console.log('收到群消息,进去处理',item)
- // event.onBigGroupMsgNotify(item)
- event.onBigGroupMsgNotify(myMsg.data)
- parseGroupSystemNotice(item.payload)
- } else if (item.payload && item.payload.data && item.payload.data.includes('InputStatus')) {
- console.log('对方键盘事件')
- } else if (item.conversationType == '@TIM#SYSTEM') {
- console.log('系统通知@_@')
- parseGroupSystemNotice(item.payload)
- } else {
- console.log('传出去了')
- handleUnreadMsg(item)
- console.log('开始传回当前页notify')
- event.onMsgNotify(item)
- }
- })
- }
- // 收到推送的单聊、群聊、群提示、群系统通知的新消息,可通过遍历 event.data 获取消息列表数据并渲染到页面
- // event.name - TIM.EVENT.MESSAGE_RECEIVED
- // event.data - 存储 Message 对象的数组 - [Message]
- }
- function parseGroupSystemNotice(payload) {
- const groupName =
- payload.groupProfile.groupName || payload.groupProfile.groupID
- console.log('审判群组消息类型', payload.operationType)
- switch (payload.operationType) {
- case 1:
- return `申请加入群组:${groupName}`
- case 2:
- event.onCustomGroupNotify(payload);
- case 3:
- return `申请加入群组:${groupName}被拒绝`
- case 4:
- return `被管理员${payload.operatorID}踢出群组:${groupName}`
- case 5:
- return `成功加入群组:${groupName}`
- case 6:
- return `${payload.operatorID}创建群:${groupName}`
- case 7:
- return `${payload.operatorID}邀请你加群:${groupName}`
- case 8:
- return `你退出群组:${groupName}`
- case 9:
- return `你被${payload.operatorID}设置为群:${groupName}的管理员`
- case 10:
- return `你被${payload.operatorID}撤销群:${groupName}的管理员身份`
- case 255:
- event.onCustomGroupNotify(payload);
- }
- }
- function loginIM(data) {
- app = getApp();
- if (app.globalData.globalWebimhandler) {
- event.onIMReady()
- event.onLoginSuccess()
- return
- }
- var loginInfo = {
- 'sdkAppID': SDKConfig.sdkappid, //用户所属应用id,必填
- 'appIDAt3rd': SDKConfig.sdkappid, //用户所属应用id,必填
- 'accountType': SDKConfig.accountType, //用户所属应用帐号类型,必填
- 'identifier': app.globalData.identifier, //当前用户ID,必须是否字符串类型,选填
- 'identifierNick': app.globalData.single.nickname || '小程序用户', //当前用户昵称,选填
- 'userSig': app.globalData.userSig, //当前用户身份凭证,必须是字符串类型,选填
- };
- console.log('开始创建im')
- tim = TIM.create({
- SDKAppID: config.sdkAppID
- })
- tim.setLogLevel(0);
- // 监听事件,例如:
- tim.on(TIM.EVENT.SDK_READY, function(msg) {
- console.log('imReady***')
- event.onIMReady()
- console.log('%%%%', event.onIMReady)
- event.onLoginSuccess && event.onLoginSuccess();
- app.globalData.globalWebimhandler = true
- });
- tim.on(TIM.EVENT.MESSAGE_RECEIVED, msgReceived);
- tim.on(TIM.EVENT.MESSAGE_REVOKED, function(event) {
- // 收到消息被撤回的通知
- // event.name - TIM.EVENT.MESSAGE_REVOKED
- // event.data - 存储 Message 对象的数组 - [Message] - 每个 Message 对象的 isRevoked 属性值为 true
- });
- tim.on(TIM.EVENT.MESSAGE_READ_BY_PEER, function(event) {
- // SDK 收到对端已读消息的通知,即已读回执。使用前需要将 SDK 版本升级至 v2.7.0 或以上。仅支持单聊会话。
- // event.name - TIM.EVENT.MESSAGE_READ_BY_PEER
- // event.data - event.data - 存储 Message 对象的数组 - [Message] - 每个 Message 对象的 isPeerRead 属性值为 true
- });
- tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, function(event) {
- console.log('监听到会话列表更新', event.data)
- // 收到会话列表更新通知,可通过遍历 event.data 获取会话列表数据并渲染到页面
- // event.name - TIM.EVENT.CONVERSATION_LIST_UPDATED
- // event.data - 存储 Conversation 对象的数组 - [Conversation]
- });
- tim.on(TIM.EVENT.GROUP_LIST_UPDATED, function(event) {
- // 收到群组列表更新通知,可通过遍历 event.data 获取群组列表数据并渲染到页面
- // event.name - TIM.EVENT.GROUP_LIST_UPDATED
- // event.data - 存储 Group 对象的数组 - [Group]
- });
- tim.on(TIM.EVENT.PROFILE_UPDATED, function(event) {
- // 收到自己或好友的资料变更通知
- // event.name - TIM.EVENT.PROFILE_UPDATED
- // event.data - 存储 Profile 对象的数组 - [Profile]
- });
- tim.on(TIM.EVENT.BLACKLIST_UPDATED, function(event) {
- // 收到黑名单列表更新通知
- // event.name - TIM.EVENT.BLACKLIST_UPDATED
- // event.data - 存储 userID 的数组 - [userID]
- });
- tim.on(TIM.EVENT.ERROR, function(event) {
- console.log('SDKERROR!!', event)
- // 收到 SDK 发生错误通知,可以获取错误码和错误信息
- // event.name - TIM.EVENT.ERROR
- // event.data.code - 错误码
- // event.data.message - 错误信息
- });
- tim.on(TIM.EVENT.SDK_NOT_READY, function(event) {
- console.log('SDK_NOT_READY!!', event)
- app.globalData.globalWebimhandler = null;
- // 收到 SDK 进入 not ready 状态通知,此时 SDK 无法正常工作
- // event.name - TIM.EVENT.SDK_NOT_READY
- });
- tim.on(TIM.EVENT.KICKED_OUT, function(event) {
- // 收到被踢下线通知
- // event.name - TIM.EVENT.KICKED_OUT
- // event.data.type - 被踢下线的原因,例如:
- // - TIM.TYPES.KICKED_OUT_MULT_ACCOUNT 多实例登录被踢
- // - TIM.TYPES.KICKED_OUT_MULT_DEVICE 多终端登录被踢
- // - TIM.TYPES.KICKED_OUT_USERSIG_EXPIRED 签名过期被踢 (v2.4.0起支持)。
- });
- tim.on(TIM.EVENT.NET_STATE_CHANGE, function(event) {
- // 网络状态发生改变(v2.5.0 起支持)。
- // event.name - TIM.EVENT.NET_STATE_CHANGE
- // event.data.state 当前网络状态,枚举值及说明如下:
- // \- TIM.TYPES.NET_STATE_CONNECTED - 已接入网络
- // \- TIM.TYPES.NET_STATE_CONNECTING - 连接中。很可能遇到网络抖动,SDK 在重试。接入侧可根据此状态提示“当前网络不稳定”或“连接中”
- // \- TIM.TYPES.NET_STATE_DISCONNECTED - 未接入网络。接入侧可根据此状态提示“当前网络不可用”。SDK 仍会继续重试,若用户网络恢复,SDK 会自动同步消息
- });
- // 开始登录
- let afterLoginIM = tim.login({
- userID: loginInfo.identifier,
- userSig: loginInfo.userSig
- });
- afterLoginIM.then((imResponse) => {
- console.log(imResponse.data, 'niubi'); // 登录成功
- if (imResponse.data.repeatLogin === true) {
- data.callback && data.callback()
- // 标识账号已登录,本次登录操作为重复登录。v2.5.1 起支持
- console.log(imResponse.data.errorInfo);
- }
- }).catch((imError) => {
- console.warn('login error:', imError); // 登录失败的相关信息
- })
- }
- function logout(callback) {
- app = getApp();
- // 退出IM登录
- tim.logout();
- console.log('imRoom总im退出登录')
- app.globalData.globalWebimhandler = null;
- callback && callback()
- }
- function sendCustomMsg(data, type, nickname, callback) {
- let message = tim.createCustomMessage({
- to: type.myselToID,
- conversationType: type.TYPE == 'C2C' ? TIM.TYPES.CONV_C2C : TIM.TYPES.GROUP,
- // 消息优先级,用于群聊(v2.4.2起支持)。如果某个群的消息超过了频率限制,后台会优先下发高优先级的消息,详细请参考 消息优先级与频率控制
- // 支持的枚举值:TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL(默认), TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
- // priority: TIM.TYPES.MSG_PRIORITY_HIGH,
- payload: {
- data: '',
- description: '',
- extension: data.ext,
- }
- });
- let promise = tim.sendMessage(message, {
- // 如果接收方不在线,则消息将存入漫游,且进行离线推送(在接收方 App 退后台或者进程被 kill 的情况下)。接入侧可自定义离线推送的标题及内容
- offlinePushInfo: {
- disablePush: false,
- title: '收到一条新消息', // 离线推送标题
- description: '请进入APP内查看', // 离线推送内容
- androidOPPOChannelID: '' // 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
- }
- });
- promise.then((imResponse) => {
- callback && callback(data)
- })
- }
- function getC2CHistoryMsgs(options) {
- console.log(tim)
- let promise = tim.getMessageList({
- conversationID: 'C2C' + options.adviserId,
- count: 10,
- nextReqMessageID: options.nextReqMessageID
- })
- promise.then((res) => {
- console.log('拉取到顾问' + options.adviserId + '的历史消息当前第' + options.nextReqMessageID + '页')
- console.log(res)
- options.success && options.success(JSON.parse(JSON.stringify(res.data)))
- }).catch((err) => {
- options.fail && options.fail(err)
- })
- }
- function onSendMsg(message, type, nickname, callback, fail) {
- let Cmessage = tim.createTextMessage({
- to: type.myselToID,
- conversationType: type.TYPE == 'C2C' ? TIM.TYPES.CONV_C2C : TIM.TYPES.GROUP,
- // 消息优先级,用于群聊(v2.4.2起支持)。如果某个群的消息超过了频率限制,后台会优先下发高优先级的消息,详细请参考 消息优先级与频率控制
- // 支持的枚举值:TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL(默认), TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
- // priority: TIM.TYPES.MSG_PRIORITY_HIGH,
- payload: {
- text: message
- }
- });
- let promise = tim.sendMessage(Cmessage);
- promise.then((imResponse) => {
- console.log('发送完毕', imResponse)
- callback && callback({
- content: message
- })
- }).catch((err) => {})
- }
- function getRecentContactList(data, callback) {
- let promise = tim.getConversationList();
- promise.then(function(imResponse) {
- const conversationList = imResponse.data.conversationList; // 会话列表,用该列表覆盖原有的会话列表
- callback && callback(conversationList.filter((item) => {
- return item.type !== '@TIM#SYSTEM'
- }))
- }).catch(function(imError) {
- console.warn('getConversationList error:', imError); // 获取会话列表失败的相关信息
- });
- }
- function onBigGroupMsgNotify() {
- }
- function parseGroupTipContent(payload) {
- switch (payload.operationType) {
- case this.TIM.TYPES.GRP_TIP_MBR_JOIN:
- return `群成员:${payload.userIDList.join(',')},加入群组`
- case this.TIM.TYPES.GRP_TIP_MBR_QUIT:
- return `群成员:${payload.userIDList.join(',')},退出群组`
- case this.TIM.TYPES.GRP_TIP_MBR_KICKED_OUT:
- return `群成员:${payload.userIDList.join(',')},被${payload.operatorID}踢出群组`
- case this.TIM.TYPES.GRP_TIP_MBR_SET_ADMIN:
- return `群成员:${payload.userIDList.join(',')},成为管理员`
- case this.TIM.TYPES.GRP_TIP_MBR_CANCELED_ADMIN:
- return `群成员:${payload.userIDList.join(',')},被撤销管理员`
- default:
- return '[群提示消息]'
- }
- }
- function setListener(options) {
- if (!options) {
- console.log('setListener参数错误', options);
- return;
- }
- event.onGetPusherList = options.onGetPusherList || function() {};
- event.onIMReady = options.onIMReady || function() {};
- event.onPusherJoin = options.onPusherJoin || function() {};
- event.onPusherQuit = options.onPusherQuit || function() {};
- event.onRoomClose = options.onRoomClose || function() {};
- event.onRecvRoomTextMsg = options.onRecvRoomTextMsg || function() {};
- event.onMsgNotify = options.onMsgNotify || function() {}; // 监听新消息(私聊(包括普通消息和全员推送消息),普通群(非直播聊天室)消息)事件,必填
- event.onDestoryGroupNotify = options.onDestoryGroupNotify || function() {}; //群被解散(全员接收) 5
- event.onCustomGroupNotify = options.onCustomGroupNotify || function() {}; //用户自定义通知(默认全员接收) 255
- event.onLoginSuccess = options.onLoginSuccess || function() {}; //IM 登录成功的回调
- event.onBigGroupMsgNotify = options.onBigGroupMsgNotify || function() {}; //监听新消息(大群)事件,必填
- }
- function applyJoinBigGroup(roomID, callback, callbackOptions) {
- let res = tim.joinGroup({
- groupID: roomID,
- applyMessage: '视频通话申请加群',
- type: TIM.TYPES.GRP_AVCHATROOM
- })
- res.then((imResponse) => {
- console.log(imResponse, '群组资料')
- switch (imResponse.data.status) {
- case TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL:
- break; // 等待管理员同意
- case TIM.TYPES.JOIN_STATUS_SUCCESS: // 加群成功
- console.log('关键步骤:加群成功!')
- callback && callback({
- errCode: 0,
- callback: callbackOptions
- });
- console.log(imResponse.data.group, '00000'); // 加入的群组资料
- break;
- case TIM.TYPES.JOIN_STATUS_ALREADY_IN_GROUP: // 已经在群中
- console.log('关键步骤:加群成功2!')
- callback && callback({
- errCode: 0,
- callback: callbackOptions
- });
- break;
- default:
- console.log('关键步骤:加群成功3!')
- break;
- }
- }).catch(function(imError) {
- console.warn('joinGroup error:', imError); // 申请加群失败的相关信息
- });
- }
- async function createBigGroup(options, cb) {
- console.log(options.roomID, '为什么要自动id?')
- // tim.createGroup({
- // groupID: options.roomID,
- // type: TIM.TYPES.GRP_AVCHATROOM,//直播群
- // maxMemberNum: 500,
- // name: options.roomName || '',
- // memberList: [],
- // }).then((imResponse) => {
- // cb(imResponse)
- // console.log(imResponse.data.group, '新版建群成功'); // 创建的群的资料
- // }).catch(function(imError) {
- // console.warn('createGroup error:', imError); // 创建群组失败的相关信息
- // })
- // 这里是管理员创建的群,已经不是当前用户创建群的逻辑了
- var res = await requestConfig('createGroup', {
- groupID: options.roomID,
- type: TIM.TYPES.GRP_AVCHATROOM,//直播群
- maxMemberNum: 500,
- name: options.roomName || '',
- memberList: []
- }, true);
- if (res && res.success) {
- cb()
- console.log(options, '新版建群成功'); // 创建的群的资料
- }
- else{
- console.warn('createGroup error:', res.message); // 创建群组失败的相关信息
- }
- }
- function quitBigGroup(groupID) {
- tim.quitGroup(groupID).then((res) => {
- console.log('退出群成功')
- });
- // var res = await requestConfig('deleteGroupMember', {
- // groupId: groupID,
- // }, true);
- }
- function destroyGroup(groupID) {
- // tim.dismissGroup(groupID).then((res) => {
- // console.log('解散群成功')
- // });
- // 管理员建群,必须是管理员销毁-此处就是调接口,让管理员销毁群
- requestConfig('destroyGroup', {
- groupId: groupID,
- }, true);
- }
- module.exports = {
- loginIM: loginIM, // 登陆IM
- setListener: setListener,
- logout: logout,
- sendCustomMsg: sendCustomMsg,
- onSendMsg: onSendMsg,
- applyJoinBigGroup: applyJoinBigGroup,
- quitBigGroup: quitBigGroup,
- destroyGroup: destroyGroup,
- getRecentContactList: getRecentContactList,
- onBigGroupMsgNotify: onBigGroupMsgNotify,
- getC2CHistoryMsgs: getC2CHistoryMsgs,
- createBigGroup: createBigGroup
- }
|