tim.js
7.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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
243
244
245
246
247
248
249
250
251
252
253
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2022-10-25 10:15:37
* @LastEditors: limin
* @LastEditTime: 2022-10-27 17:36:43
* @FilePath: \scrm-wx-merchant-activity\src\components\TIM\im.js
*/
// 从v2.11.2起,SDK 支持了 WebSocket,推荐接入;v2.10.2及以下版本,使用 HTTP
import TIM from 'tim-wx-sdk'
import TIMUploadPlugin from 'tim-upload-plugin'
const TimOptions = {
// SDKAppID: 1400743527
}
export default class IM {
constructor(options = {}) {
this.loginResolveRejectCache = []
this.options = Object.assign({}, TimOptions, options)
this.isSDKReady = false
this.isLogin = false
this.init()
this.bindTIMEvent()
}
init() {
// 创建 SDK 实例,`TIM.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例
this.tim = TIM.create({ SDKAppID: this.options.SDKAppID }) // SDK 实例通常用 tim 表示
// 设置 SDK 日志输出级别,详细分级请参见 <a href="https://web.sdk.qcloud.com/im/doc/en/SDK.html#setLogLevel">setLogLevel 接口的说明</a>
this.tim.setLogLevel(1) // 普通级别,日志量较多,接入时建议使用
// tim.setLogLevel(1); // release 级别,SDK 输出关键信息,生产环境时建议使用
// 注册腾讯云即时通信 IM 上传插件
this.tim.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin })
}
/**
* 绑定tim回调事件
*/
bindTIMEvent() {
this.tim.on(TIM.EVENT.SDK_READY, this.handleSDKReady, this)
this.tim.on(TIM.EVENT.MESSAGE_RECEIVED, this.onMessageReceived, this)
this.tim.on(TIM.EVENT.NET_STATE_CHANGE, this.onNetStateChange, this)
}
/**
* 登录
* @param {*} userID 用户唯一id
* @param {*} userSig 生成签名
* @returns
*/
login(userID, userSig) {
return new Promise((resolve, reject) => {
if (!userID) {
reject('userID is not be blank')
return null
}
if (!userSig) {
reject('userSig is not be blank')
return null
}
this.tim
.login({ userID, userSig })
.then(() => {
this.loginResolveRejectCache.push({ resolve, reject })
this.isLogin = true
return null
})
.catch(reject)
})
}
/** 更新用户标配信息
* nick,avatar,gender,selfSignature,allowType
*/
updateMyProfile(obj) {
let promise = this.tim.updateMyProfile(obj);
promise.then(function (imResponse) {
console.log(imResponse.data); // 更新资料成功
}).catch(function (imError) {
console.warn('updateMyProfile error:', imError); // 更新资料失败的相关信息
});
}
/**
* 加入群聊
* @returns Promise
*/
joinGroup(groupID, type = TIM.TYPES.GRP_AVCHATROOM) {
return new Promise((resolve, reject) => {
this.options.groupID = groupID
let promise = this.tim.joinGroup({ groupID, type })
promise
.then(function (imResponse) {
switch (imResponse.data.status) {
case TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL: // Waiting to be approved by the admin
console.info('Waiting to be approved by the admin') // Profile of the group
resolve('Waiting to be approved by the admin')
break
case TIM.TYPES.JOIN_STATUS_SUCCESS: // Joined the group successfully
console.info('Joined the group successfully') // Profile of the group
resolve(imResponse.data.group)
break
case TIM.TYPES.JOIN_STATUS_ALREADY_IN_GROUP: // The user is already in the group
console.info('The user is already in the group')
resolve('The user is already in the group')
break
default:
reject(imResponse.data.status)
break
}
})
.catch(function (imError) {
console.warn('joinGroup error:', imError) // Error information
reject('joinGroup error:' + imError)
})
})
}
quitGroup(groupID) {
if (!groupID) {
throw new Error('groupID is not be blank')
}
return this.tim.quitGroup(groupID)
}
/**
* 登录并加入群聊
* @param {*} param0
* @returns
*/
join({ userID, userSig, groupID }) {
if (!userID) {
throw new Error('userID is not be blank')
}
if (!userSig) {
throw new Error('userSig is not be blank')
}
if (!groupID) {
throw new Error('groupID is not be blank')
}
return this.login(userID, userSig).then(() => this.joinGroup(groupID))
}
/**
* 退出群聊,并退出登录
*/
quit() {
return this.quitGroup(this.options.groupID).then(() => this.logout())
}
/**
* 登出
* @returns Promise
*/
logout() {
return new Promise((resolve, reject) => {
this.tim
.logout()
.then(imResponse => {
this.isSDKReady = false
this.isLogin = false
resolve(imResponse)
})
.catch(reject)
})
}
/**
* (内部)登录成功,且SDK Ready
*/
handleSDKReady() {
this.isSDKReady = true
this.loginResolveRejectCache.forEach(({ resolve }) => {
resolve({
msg: '登录成功,且SDK Ready'
})
})
}
destroy() {
return this.tim.destroy()
}
/**
* 收到新消息回调
* @param {*} event 回调消息体
*/
onMessageReceived(event) {
this.options.onMessageReceived(event.data)
}
/**
* 网络波动回调
* @param {*} event 回调消息体
*/
onNetStateChange(event) {
// v2.5.0 起支持
// event.data.state 当前网络状态,枚举值及说明如下:
// TIM.TYPES.NET_STATE_CONNECTED - 已接入网络
// TIM.TYPES.NET_STATE_CONNECTING - 连接中。很可能遇到网络抖动,SDK 在重试。接入侧可根据此状态提示“当前网络不稳定”或“连接中”
// TIM.TYPES.NET_STATE_DISCONNECTED - 未接入网络。接入侧可根据此状态提示“当前网络不可用”。SDK 仍会继续重试,若用户网络恢复,SDK 会自动同步消息
let notify = {}
switch (event.data.state) {
case TIM.TYPES.NET_STATE_CONNECTED:
notify = { message: '已接入网络', type: 'success' }
break
case TIM.TYPES.NET_STATE_CONNECTING:
notify = { message: '连接中', type: 'warning' }
break
case TIM.TYPES.NET_STATE_DISCONNECTED:
notify = { message: '当前网络不可用', type: 'danger' }
break
default:
break
}
this.options.onNetStateChange(notify)
}
/**
* 发送一条消息
* @param {*} msg 消息内容
* @returns Promise
*/
send(msg) {
return new Promise((resolve, reject) => {
const message = this.createMessage(msg)
this.sendMessage(message)
.then(event => {
this.onMessageReceived(Object.assign({}, event, { data: [event.data.message] }))
resolve(event)
})
.catch(reject)
})
}
/**
* (内部)组装一条tim TEXT 消息体
* @param {*} msg 消息内容
* @returns 组装好的消息
*/
createMessage(msg) {
let message = this.tim.createTextAtMessage({
to: this.options.groupID,
conversationType: TIM.TYPES.CONV_GROUP,
payload: {
text: msg
}
})
return message
}
/**
* (内部)发送一条消息
* @param {*} message 组装好的tim消息内容
* @returns Promise
*/
sendMessage(message) {
return this.tim.sendMessage(message)
}
}