├── CHANGELOG.md
├── README.md
├── bower.json
├── engine.js
└── engine.min.js
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | ## Change Log
2 |
3 | 2.1.0:
4 |
5 | * 新增: `Chat` 离线功能
6 |
7 | 2.0.0:
8 |
9 | * 新增:`Chat` 多媒体消息,可发送图片、语音、视频、地理位置等,丰富聊天内容
10 | * 新增:`Chat` 缓存,可对群组、会话和消息进行本地缓存,节省网络流量
11 | * 新增:`Chat` 消息可携带附加信息,用以实现应用自定义业务逻辑
12 | * 更新:`Pub/Sub` 及 `Chat` 原有 `API` 被按功能分发到各个子模块
13 | * 更新:`Chat` 移除了 `Chat Group` 的 `name`, `description` 属性
14 |
15 | 1.0.0:
16 |
17 | * 更新:`Chat` 获取当前用户及登录状态 `API`
18 |
19 | 0.9.2:
20 |
21 | * 修复:`Presence Channel users.me` 为空
22 |
23 | 0.9.1:
24 |
25 | * 新增:`Chat` 应用模式
26 |
27 | 0.9.0:
28 |
29 | * 新增:`Connection` 实时连接
30 | * 新增:`Pub/Sub` 应用模式
31 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | 阅读此文档前,请先阅读 [实时引擎指南](docs/engineGuide) 。
4 |
5 |
6 | ## 浏览器兼容
7 |
8 | 基本功能兼容 IE8+ 以及各种最新版的现代浏览器,包括 Chrome 、 FireFox 、 Safari 等。
9 |
10 | *Chat* 模式语音、视频消息的录制发送仅支持 Chrome、 Firefox 。
11 |
12 | ## API 文档
13 |
14 | 本指南只给出简要集成说明,具体使用时请参考 [API 文档](docs/engineAPI/clientJavaScript)
15 |
16 | ## 安装
17 |
18 | 
19 |
20 | 从 [这里](downloadSDK/engine##javascript) 下载,或者使用 bower 安装:
21 |
22 | ```bash
23 | bower install tuisongbao-realtime-engine-client
24 | ```
25 |
26 | 然后引用安装目录下的 `engine.js` 或 `engine.min.js` 即可:
27 |
28 | ```html
29 |
30 | ```
31 |
32 | ## 预备知识
33 |
34 | - 在浏览器开发者工具 Console 中运行 `Engine.debug.enable('engine:*')` 可以启用调试日志,要停用运行 `Engine.debug.disable()` 即可。
35 |
36 | ## 配置并建立连接
37 |
38 | 实例化 `Engine` 时可以通过第二个参数传递各种选项:
39 |
40 | ```js
41 | var options = {
42 | // 认证用户的地址
43 | authEndpoint: 'http://yourdomain.com/tuisongbao_engine/auth',
44 | // 认证用户请求方式,默认为 `xhr` ,使用 XMLHttpRequest ,但是该方式在 IE8/9 上存在跨域问题,如果你配置的 authEndpoint 跨域并且需要支持 IE8/9 ,应使用 `jsonp` ,同时请确保你的服务端支持 `jsonp` 请求,该设置在所有浏览器上生效,并非仅在 IE8/9 上生效
45 | authTransport: 'jsonp',
46 | // 可选,如果配置,认证请求将携带该值,可以用来表明用户身份。当结合 jsonp 使用时,该值如果为 Object ,会被序列化成 JSON 字符串。
47 | authData: 'authData-sample'
48 | // 使用扩展功能(Chat 本地缓存,多媒体消息)时必须指定 engine.js 在 Web 服务器上的父级路径
49 | basePath: '/engine/clientJavaScript/',
50 | // 可选, 作用是在网络不可用时, SDK 支持某些 API 的调用。详情请参照 Chat 章的缓存策略
51 | supportOffline: true,
52 | // Chat 相关选项,不使用 Chat 模式则无需配置
53 | chat:
54 | // 开启本地缓存, 此功能支持 Chrome, Firefox, IE11
55 | enableCache: true,
56 | // 启用多媒体消息(图片,语音,视频)发送功能,开启此选项将会异步加载额外的资源文件
57 | enableMediaMessage: true
58 | };
59 |
60 | var engine = new Engine('YOUR_APP_ID', options);
61 | ```
62 |
63 | 实例化后,连接将自动建立,你可以使用返回的 `Engine` 实例进行后续各种操作。
64 |
65 | ### Connection Event
66 |
67 | 在 `engine.connection` 对象上,可以监听如下 *Event* :
68 |
69 | - `state_changed` :连接状态变化时触发。
70 | - `connecting_in` :通知下次重连是在多久以后。
71 | - 以及 `initialized`, `connected`, `disconnected`, `connecting`, `failed`,分别于 `Connection` 进入该状态时触发。
72 | - `error` :连接发生错误时触发。
73 |
74 | ```js
75 | connection.bind('state_changed', function (states) {
76 | console.log(states.previous, states.current);
77 | });
78 |
79 | connection.bind('connecting_in', function (delay) {
80 | console.log('重连将在 ' + delay + 'ms 后进行');
81 | });
82 |
83 | connection.bind('connecting', function () {
84 | // 提醒用户网络不稳定,正在尝试建立连接
85 | });
86 |
87 | connection.bind('error', function (err) {
88 | console.log(err);
89 | });
90 | ```
91 |
92 | ### 获取 SocketId
93 |
94 | ```js
95 | connection.bind('connected', function () {
96 | console.log(connection.socketId);
97 | });
98 | ```
99 |
100 | ### 断开连接
101 |
102 | 在 `connection` 对象上调用 `disconnect` 即可:
103 |
104 | ```js
105 | connection.disconnect();
106 | ```
107 |
108 | 若要恢复连接,调用 `connect` :
109 |
110 | ```js
111 | connection.connect();
112 | ```
113 |
114 | ## Pub/Sub
115 |
116 | *Pub/Sub* 相关功能主要通过 `engine.channels` 完成。
117 |
118 | ### 获得 channel 管理对象 channels
119 |
120 | ```js
121 | var channels = engine.channels;
122 | ```
123 |
124 | ### 订阅 Channel
125 |
126 | ```js
127 | var coolChannel = channels.subscribe('cool-channel');
128 | ```
129 |
130 | 该方法返回 `Channel` 实例,可用于 `bind` 等操作。
131 |
132 | 另外也可以通过 `channels` 的 `find` 方法获取已订阅的 `Channel` 实例:
133 |
134 | ```js
135 | var coolChannel = channels.find('cool-channel');
136 | ```
137 |
138 | 使用 `unsubscribe` 方法来取消订阅:
139 |
140 | ```js
141 | channels.unsubscribe('cool-channel');
142 | ```
143 |
144 | ### 绑定 Event 处理函数
145 |
146 | ```js
147 | coolChannel.bind('cool-event', function (data) {
148 | // 处理逻辑
149 | });
150 | ```
151 |
152 | 该操作只应用于当前 `Channel`,也就是说你可以在其他 `Channel` 上使用相同的 *Event* 名字。
153 |
154 | 使用 `unbind` 方法来解除绑定:
155 |
156 | ```js
157 | // 只解绑这个 Event 的某个处理函数
158 | coolChannel.unbind('cool-channel', handler);
159 | // 解绑这个 Event 的所有处理函数
160 | coolChannel.unbind('cool-channel');
161 | ```
162 |
163 | ### Channel Event
164 |
165 | 所有 `Channel` 都可以通过监听 `engine:subscription_succeeded` 和 `engine:subscription_error` *Event* 来处理订阅结果:
166 |
167 | ```js
168 | privateChannel.bind('engine:subscription_succeeded', function () {
169 | console.log('订阅 channel ' + privateChannel.name + ' 成功');
170 | });
171 |
172 | privateChannel.bind('engine:subscription_error', function (err) {
173 | console.log('订阅 channel ' + privateChannel.name + ' 失败', err);
174 | // 重新 subscribe ?
175 | });
176 | ```
177 |
178 | 对于 *Presence Channel* , `engine:subscription_succeeded` 处理函数将得到一个额外的参数 `users` ,该对象具有以下属性:
179 |
180 | ```js
181 | {
182 | // 该 Channel 上的当前在线用户数
183 | count: 100,
184 | // 接收一个方法作为参数,用来遍历当前在线用户
185 | each: [Function],
186 | // 当前用户
187 | me: {
188 | id: '1111',
189 | info: 'Fake user info for socket 111111 on channel presence-demo'
190 | }
191 | }
192 | ```
193 |
194 | 示例如下:
195 |
196 | ```js
197 | presenceChannel.bind('engine:subscription_succeeded', function (users) {
198 | console.log('订阅 channel ' + presenceChannel.name + ' 成功');
199 | console.log('用户量:' + users.count);
200 |
201 | console.log('遍历用户开始:');
202 | users.each(function (user) {
203 | console.log(user.id, user.info);
204 | });
205 | console.log('遍历用户结束');
206 |
207 | console.log('当前用户:', users.me.id, users.me.info);
208 | });
209 | ```
210 |
211 | 注意, `users` 对象也可以直接从 *Presence Channel* 对象上获取:
212 |
213 | ```js
214 | console.log(presenceChannel.users);
215 | ```
216 |
217 | 此外,可以在 *Presence Channel* 对象上监听 `engine:user_added` 和 `engine:user_removed` 来处理用户上下线通知:
218 |
219 | ```js
220 | presenceChannel.bind('engine:user_added', function (user) {
221 | console.log('新用户:', user.id, user.info);
222 | });
223 |
224 | presenceChannel.bind('engine:user_removed', function (user) {
225 | console.log('用户离开:', user.id, user.info);
226 | });
227 | ```
228 |
229 | ## Chat
230 |
231 | *Chat* 相关功能主要通过 `engine.chatManager` 完成。
232 |
233 | #### ChatManager Event
234 |
235 | ```js
236 | chatManager.bind('login:succeeded', function() {
237 | console.log('登录成功');
238 | });
239 |
240 | chatManager.bind('login:failed', function(err) {
241 | console.log('登录失败');
242 | });
243 |
244 | chatManager.bind('message:new', function(message) {
245 | console.log('新消息');
246 | });
247 | ```
248 |
249 | 更多 *Event* 请参考 [API 文档](docs/engineAPI/clientJavaScript/) 。
250 |
251 | ### 用户相关
252 |
253 | #### 登录
254 |
255 | ```js
256 | chatManager.login({
257 | authData: chatUserId
258 | });
259 |
260 | var onLoginSucceeded = function() {
261 | console.log('login succeeded');
262 | };
263 | var onLoginError = function(err) {
264 | console.log('login failed:', err);
265 | };
266 |
267 | engine.chatManager.bind('login:succeeded:', onLoginSucceeded);
268 | engine.chatManager.bind('login:failed:', onLoginError);
269 | ```
270 |
271 | #### 登出
272 |
273 | ```js
274 | chatManager.logout().then(function() {
275 | console.log('登出成功');
276 | }).catch(function(err){
277 | console.log('登出失败' + err);
278 | });
279 | ```
280 |
281 | #### 获取当前用户及登录状态
282 |
283 | ```js
284 | // 内容为认证用户时你的服务端所返回的 userData
285 | console.log(engine.chatManager.user);
286 |
287 | // 枚举值: initialized, loggingIn, loggedIn, failed, loggedOut
288 | console.log(engine.chatManager.state);
289 | ```
290 |
291 | ### 会话相关
292 |
293 | #### 获取会话列表
294 |
295 | 通过 `chatManager.conversations` 来获取会话列表。
296 |
297 | Promise 写法:
298 |
299 | ```js
300 | conversations.load().then(function(conversations) {
301 | console.log('成功获取 Conversation 实例的列表');
302 | }).catch(function(err) {
303 | console.log('获取失败,请稍后再试');
304 | });
305 | ```
306 |
307 | 回调写法:
308 |
309 | ```js
310 | conversations.load({
311 | onSuccess: function(conversations) {
312 | console.log('成功获取 Conversation 实例的列表');
313 | },
314 | onError: function(err) {
315 | console.log('获取失败,请稍后再试');
316 | }
317 | });
318 | ```
319 |
320 | 关于 Promise 和 回调的说明,请查看[此处](docs/engineGuide/clientJavaScript##%23%23%E8%A1%A5%E5%85%85%E8%AF%B4%E6%98%8E)。
321 |
322 | #### 获取 ChatConversation 的实例
323 |
324 | 开发者可以调用 `ChatConversation` 实例上的方法实现发送消息,删除会话,重置未读消息等功能,它可以像上面的例子一样从会话列表中获得,也可以通过 `conversations.loadOne` 获取特定的会话:
325 |
326 | ```js
327 | conversations.loadOne({
328 | type: 'singleChat',
329 | target: '1111'
330 | }).then(function(_conversation) {
331 | conversation = _conversation
332 | });
333 | ```
334 |
335 | #### 获取会话历史消息
336 |
337 | ```js
338 | conversation.loadMessages({
339 | // Conversation 类型, singleChat(单聊)或 groupChat(群聊)
340 | type: 'singleChat',
341 | // 跟谁(聊天另一方的 ID), userId 或 groupId
342 | target: '1111',
343 | // 可选
344 | startMessageId: 100,
345 | // 可选
346 | endMessageId: 300,
347 | // 可选,默认 20,最大 100
348 | limit: 20
349 | // 其他参数请参照 API 文档
350 | }).then(function(messages) {
351 | console.log('成功获取会话消息');
352 | // 在开启支持离线功能时,离线存储的 message 包含三个状态 `sending`, `succeeded`, `failed` 。当状态为 `sending` 时会在调用 loadMessages 之前重发消息,过程中可能导致 message 状态改变,如果需要跟踪 message 的状态,你可以监听 `state:changed` 事件
353 | messages.map(function (message){
354 | if(message.state !== 'succeeded'){
355 | message.bind('state:changed', function (state){
356 | // Message 状态改变, 刷新 UI 的逻辑可以写在这里
357 | console.log("变化前的状态:", state.previous);
358 | console.log("当前状态", state.current);
359 | });
360 | }
361 | });
362 | }).catch(function(err) {
363 | console.log('获取失败,请稍后再试');
364 | });
365 | ```
366 |
367 | #### 将会话未读消息数重置为 0
368 |
369 | ```js
370 | conversation.resetUnread();
371 | ```
372 |
373 | #### 删除会话
374 |
375 | ```js
376 | conversation.delete().then(function() {
377 | console.log('成功删除会话');
378 | }).catch(function(err) {
379 | console.log('操作失败,请稍后再试');
380 | });
381 | ```
382 |
383 | ### 消息相关
384 |
385 | #### 监听新消息
386 |
387 | 通过在 `ChatConversation` 对象上监听 `message:new` *Event* 来监听新消息:
388 |
389 | ```js
390 | conversation.bind('message:new', function(newMessage) {
391 | console.log('你收到一条来自的' + newMessage.from + '的新消息');
392 |
393 | // type 枚举: 'text', 'image', 'voice', 'video', 'location', 'event'
394 | console.log('消息的类型为:' + newMessage.content.type);
395 |
396 | if (newMessage.content.file) {
397 | console.log('多媒体文件下载地址:' + newMessage.content.file.url);
398 | console.log('多媒体文件大小:' + newMessage.content.file.size);
399 | } else if (newMessage.content.location) {
400 | console.log('地理位置为(兴趣点):' + newMessage.content.location.poi);
401 | } else if (newMessage.content.event) {
402 | console.log(' Event 类型为:' + newMessage.content.event.type);
403 | } else {
404 | console.log('你发的是文本消息, 内容为:' + newMessage.content.text);
405 | }
406 | console.log('附加信息:' + newMessage.content.extra);
407 | console.log('发送时间:' + newMessage.createdAt);
408 | });
409 | ```
410 |
411 | #### 发送文本消息
412 |
413 | ```js
414 | conversation.sendMessage({
415 | type: 'text',
416 | text: 'Hello World!',
417 | // 可选,附加信息,用于实现应用自定义业务逻辑
418 | extra: {}
419 | }).then(function(message) {
420 | console.log(message);
421 | }).catch(function(err) {
422 | console.log('发送失败,请稍后再试');
423 | });
424 | ```
425 |
426 | #### 发送图片消息
427 |
428 | #### 获取 ImageUploader
429 |
430 | ```js
431 | conversation.getImageUploader({
432 | // 触发文件选择的 DOM 元素的 ID
433 | browseButton: 'imageMessage',
434 | // 可选,拖曳区域的 DOM 元素的 ID,可实现拖曳上传
435 | dropElementId: 'messageContainer',
436 | // 可选,附加信息,用于实现应用自定义业务逻辑
437 | extra: {}
438 | }).then(function(imageUploader) {
439 | console.log('成功获取了 imageUploader,可以在上面监听 Event 了');
440 | }).catch(function(err) {
441 | console.log('操作失败,请稍后再试');
442 | });
443 | ```
444 |
445 | 初始化后,用户点击 `browseButton` 会弹出文件选择对话框,当用户选择文件后, 文件会自动上传并发送消息。
446 |
447 | #### 可以在 ImageUploader 上绑定相关的 Event 处理函数
448 |
449 | ```js
450 | imageUploader.bind('failed', function(err) {
451 | console.log('imageUploader 初始化失败:' + err);
452 | });
453 | imageUploader.bind('message:sent', function(sentMessage) {
454 | console.log('发送图片消息成功:' + sentMessage);
455 | });
456 | imageUploader.bind('message:sendFailed', function(err) {
457 | console.log('发送图片消息失败:' + err);
458 | });
459 | imageUploader.bind('state:changed', function(state) {
460 | // state 的可能取值为: initialized(初始化完成),uploaded(上传成功),uploading(正在上传),failed(初始化失败)
461 | console.log('上传图片消息的状态:' + state);
462 | });
463 | ```
464 |
465 | #### 销毁对象
466 |
467 | ```js
468 | // 解绑这个 Event 的所有处理函数, 并销毁 imageUploader 这个对象和相应文件选择的 DOM 节点
469 | imageUploader.destroy()
470 | ```
471 |
472 | #### 发送语音消息
473 |
474 | 发送语音消息是通过 `VoiceUploader` 来完成的
475 |
476 | `VoiceUploader` 提供了一系列发送语音消息的方法,详见 [API](docs/engineAPI/clientJavaScript/index.html#ChatVoiceUploader)
477 |
478 | - `startRecord`: 开始录制语音
479 | - `stopRecord`: 停止录制语音
480 | - `send`: 发送录制的语音
481 |
482 | #### 获取 VoiceUploader
483 |
484 | ```js
485 | conversation.getVoiceUploader({
486 | // 可选,附加信息,用于实现应用自定义业务逻辑
487 | extra: {}
488 | }).then(function(voiceUploader) {
489 | console.log('成功获取了 voiceUploader,可以在上面监听 Event 了');
490 | }).catch(function(err) {
491 | console.log('操作失败,请稍后再试');
492 | });
493 | ```
494 |
495 | #### 通过 VoiceUploader 可以绑定相关 Event 处理函数
496 |
497 | ```js
498 | voiceUploader.bind('failed', function(err) {
499 | console.log('VoiceUploader 初始化失败:' + err);
500 | });
501 | voiceUploader.bind('message:sent', function(sentMessage) {
502 | console.log('发送语音消息成功:' + sentMessage);
503 | });
504 | voiceUploader.bind('message:sendFailed', function(err) {
505 | console.log('发送语音消息失败:' + err);
506 | });
507 | voiceUploader.bind('state:changed', function(state) {
508 | // state 的可能取值为: initialized(初始化完成),recording(正在录制),recorded(录制成功),uploaded(上传成功),uploading(正在上传),failed(初始化失败)
509 | console.log('录制、上传语音消息的状态:' + state);
510 | });
511 | voiceUploader.bind('record:started', function() {
512 | console.log('录制开始');
513 | });
514 | voiceUploader.bind('record:stopped', function(blob, duration) {
515 | console.log('录制结束,返回 blob 对象和时长');
516 | });
517 | ```
518 |
519 | #### 销毁对象
520 |
521 | ```js
522 | // 解绑这个 Event 的所有处理函数, 并销毁 voiceUploader 对象
523 | voiceUploader.destroy()
524 | ```
525 |
526 | #### 发送视频消息
527 |
528 | 发送视频消息是通过 `VideoUploader` 来完成的
529 |
530 | `VideoUploader` 提供了一系列发送视频消息的方法,详见 [API](docs/engineAPI/clientJavaScript/index.html#ChatVideoUploader)
531 |
532 | - `startRecord`: 开始录制视频
533 | - `stopRecord`: 停止录制视频
534 | - `send`: 发送录制的视频
535 |
536 | #### 获取 VideoUploader
537 |
538 | ```js
539 | conversation.getVideoUploader().then(function(videoUploader) {
540 | console.log('成功获取 videoUploader,可以在上面监听 Event 了');
541 | }).catch(function(err) {
542 | console.log('操作失败,请稍后再试');
543 | });
544 | ```
545 |
546 | #### 通过 VideoUploader 可以绑定相关 Event 处理函数
547 |
548 | ```js
549 | videoUploader.bind('failed', function(err) {
550 | console.log('VideoUploader 初始化失败:' + err);
551 | });
552 | videoUploader.bind('message:sent', function(sentMessage) {
553 | console.log('发送视频消息成功:' + sentMessage);
554 | });
555 | videoUploader.bind('message:sendFailed', function(err) {
556 | console.log('发送视频消息失败:' + err);
557 | });
558 | videoUploader.bind('state:changed', function(state) {
559 | // state 的可能取值为: initialized(初始化完成),recording(正在录制),recorded(录制成功),uploaded(上传成功),uploading(正在上传),failed(初始化失败)
560 | console.log('录制、上传视频消息的状态:' + state);
561 | });
562 | voiceUploader.bind('record:started', function() {
563 | console.log('录制开始');
564 | });
565 | videoUploader.bind('record:stopped', function(blob, duration) {
566 | console.log('录制结束,返回 blob 对象和时长');
567 | })
568 | ```
569 |
570 | ```js
571 | // 解绑所有的 Event,并销毁 videoUploader 这个对象和相应录制视频的 DOM 节点
572 | videoUploader.destroy()
573 | ```
574 |
575 | #### 发送地理位置消息
576 |
577 | ```js
578 | chatManager.locationHelper.getLocation().then(function(location) {
579 | // 返回当前的位置的经纬度
580 | console.log('当前的位置是:' + location);
581 | // 发送地理位置消息
582 | conversation.sendMessage({
583 | type: 'location',
584 | location: {
585 | // 纬度
586 | lat: location.lat
587 | // 经度
588 | lng: location.lng
589 | // 可选,兴趣点,如果不填,推送宝将尝试从百度地图获取
590 | poi: location.poi
591 | },
592 | // 可选,附加信息,用于实现应用自定义业务逻辑
593 | extra: {}
594 | }).then(function(message) {
595 | console.log(message);
596 | }).catch(function() {
597 | console.log('发送失败,请稍后再试');
598 | });
599 | }).catch(function(err) {
600 | console.log('err: ' + err);
601 | });
602 | ```
603 |
604 | ### 群组相关
605 |
606 | #### 获取群组列表
607 |
608 | 通过 `chatManager.groups` 可以获取群组列表:
609 |
610 | ```js
611 | // 无参数,该接口用来同步最新的群组列表
612 | chatManager.groups.load({
613 | // 可选,根据 id 过滤
614 | groupId: '54c4951f50c5e752c0a512a1'
615 | }).then(function(groups) {
616 | console.log(groups);
617 | }).catch(function(err) {
618 | console.log('获取失败,请稍后再试');
619 | });
620 | ```
621 |
622 | #### 创建群组
623 |
624 | ```js
625 | chatManager.groups.create({
626 | // 群组是否公开(true:任何用户的加群请求都会直接通过,无需审核; false:需要管理者审核)
627 | isPublic: true,
628 | // 除创建者(owner)外,其他群用户是否可以可以发送加群邀请(true:可以; false:不可以)
629 | userCanInvite: true
630 | // 初始成员, 创建成功后会向这些用户发送群组邀请,若被邀请者的 acceptAllJoinGroupInvitation 为 true 时直接加入该组
631 | inviteUserIds: ['1111', '2222']
632 | }).then(function(_group) {
633 | group = _group;
634 | }).catch(function(err) {
635 | console.log('创建失败,请稍后再试');
636 | });
637 | ```
638 |
639 | #### 获取群组用户列表
640 |
641 | ```js
642 | group.loadUsers().then(function(users) {
643 | console.log('成功获取群组用户');
644 | }).catch(function(err) {
645 | console.log('获取失败,请稍后再试');
646 | });
647 | ```
648 |
649 | `users` 结构:
650 |
651 | ```js
652 | [{
653 | userId: '1111',
654 | // 在线状态,online 或 offline
655 | presence: 'online'
656 | }]
657 | ```
658 |
659 | #### 邀请用户加入群组
660 |
661 | ```js
662 | group.inviteUsers({
663 | userIds: ['1111']
664 | }).then(function() {
665 | console.log('成功获取群组用户');
666 | }).catch(function(err) {
667 | console.log('获取失败,请稍后再试');
668 | });
669 | ```
670 |
671 | #### 将用户移出群组
672 |
673 | ```js
674 | group.removeUsers({
675 | userIds: ['1111']
676 | }).then(function(users) {
677 | console.log('成功移出用户');
678 | }).catch(function(err) {
679 | console.log('操作失败,请稍后再试');
680 | });
681 | ```
682 |
683 | #### 主动离开群组
684 |
685 | ```js
686 | group.leave().then(function() {
687 | console.log('成功离开群组');
688 | }).catch(function(err) {
689 | console.log('操作失败,请稍后再试');
690 | });
691 | ```
692 |
693 | ### 补充说明
694 |
695 | #### 关于 Promise
696 |
697 | `ChatManager` 中除了 `login` 外所有的方法都支持 `promise` 和回调两种异步书写方式,具体请查阅 [API 文档](docs/engineAPI/clientJavaScript/) 。
698 |
699 | #### 关于 Event
700 |
701 | `ChatManager`, `ChatConversation`, `ChatUploader` 等均继承于 [EventEmitter](docs/engineAPI/clientJavaScript/index.html#EventEmitter),因此在这些对象上均可使用 `bind` 方法绑定事件处理函数和 `unbind` 方法解绑事件处理函数。
702 |
703 | #### 关于消息的附加信息 extra
704 |
705 | 所有消息类型均支持 extra,用以实现应用自定义的业务逻辑。
706 |
707 | #### 关于权限
708 |
709 | 发送语言、视频、地理位置消息时需要向浏览器请求相应的权限, SDK 会适时的向浏览器发送该请求,只有用户同意之后才能正常发送消息。
710 |
711 | ### 注意事项
712 |
713 | - 除了登录之外,所有 API 都 **必须** 在用户成功登录之后再调用,否则会返回错误。
714 |
715 | ## 升级步骤
716 |
717 | ### v1.0.0 至 2.0.0
718 |
719 | - 替换 `engine.js`
720 | - pub/sub 相关的方法被移至 `engine.channels` 上
721 | - `ChatManager` 上除 `login`, `logout` 外所有 API 都按功能分发到各个子模块,参见 [API 文档](docs/engineAPI/clientJavaScript/)
722 |
723 | ### v0.9.2 至 1.0.0
724 |
725 | - 替换 `engine.js` 即可
726 | - `chatManager`:
727 | - 移除了 `chatManager.loggedIn` ,新增 `chatManager.state`
728 |
--------------------------------------------------------------------------------
/bower.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "tuisongbao-realtime-engine-client",
3 | "version": "v2.1.0",
4 | "authors": [
5 | "inetfuture(Aaron Wang) "
6 | ],
7 | "description": "Tuisongbao Realtime Engine JavaScript Client SDK",
8 | "main": "engine.min.js",
9 | "keywords": [
10 | "tuisongbao",
11 | "realtime",
12 | "engine"
13 | ],
14 | "license": "MIT",
15 | "ignore": [
16 | "**/.*",
17 | "node_modules",
18 | "bower_components",
19 | "app/bower_components",
20 | "test",
21 | "tests"
22 | ]
23 | }
24 |
--------------------------------------------------------------------------------
/engine.min.js:
--------------------------------------------------------------------------------
1 | !function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;gb;b++)d=a[b],this._users[d.userId]=this._formatUser(d),this.count++;return this.me=this.get(this._myId)},a.prototype.addUser=function(a){return this._users[a.userId]||this.count++,this._users[a.userId]=this._formatUser(a),this.get(a.userId)},a.prototype.removeUser=function(a){return a=this._users[a.userId],a&&(delete this._users[a.userId],this.count--),a},a.prototype.each=function(a){var b,c,d,e;b=this._users,c=[];for(e in b)d=b[e],c.push(a(d));return c},a.prototype.get=function(a){return this._users[a]},a}(),b.exports=d},{}],7:[function(a,b,c){"use strict";var d,e,f,g,h,i=function(a,b){function c(){this.constructor=a}for(var d in b)j.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},j={}.hasOwnProperty;h=a("debug")("engine:chat:confirmAlert"),g=a("../chatManagerUtil"),f=a("../../utils/promise"),e=a("./eventAlert"),d=function(a){function b(){return b.__super__.constructor.apply(this,arguments)}return i(b,a),b.prototype.accept=function(a){var b;return a.alertId=this.alertId,a.alertType=function(){switch(this.type){case"group:joinInvitation:new":return"group:joinInvitation:accepted"}}.call(this),b=g.getPromiseOption(a),this._accept(b).then(function(b){return function(){var c;return(null!=(c=b.engine.options.chat)?c.enableCache:void 0)?b._updateCacheWithStatus("processed"):"function"==typeof a.onSuccess?a.onSuccess():void 0}}(this)).then(function(){return"function"==typeof a.onSuccess?a.onSuccess():void 0})["catch"](function(b){return"function"==typeof a.onError?a.onError(b):void 0})},b.prototype.reject=function(a){var b;return a.alertId=this.alertId,a.alertType=function(){switch(this.type){case"group:joinInvitation:new":return"group:joinInvitation:rejected"}}.call(this),b=g.getPromiseOption(a),this._reject(b).then(function(b){return function(){var c;return(null!=(c=b.engine.options.chat)?c.enableCache:void 0)?b._updateCacheWithStatus("processed"):"function"==typeof a.onSuccess?a.onSuccess():void 0}}(this)).then(function(){return"function"==typeof a.onSuccess?a.onSuccess():void 0})["catch"](function(b){return"function"==typeof a.onError?a.onError(b):void 0})},b.prototype._accept=function(a){return this.engine.chatManager.request("engine_chat:alert:accept",a)},b.prototype._reject=function(a){return this.engine.chatManager.request("engine_chat:alert:reject",a)},b}(e),f.toPromise(d),b.exports=d},{"../../utils/promise":32,"../chatManagerUtil":10,"./eventAlert":8,debug:38}],8:[function(a,b,c){"use strict";var d,e,f,g;g=a("debug")("engine:chat:eventAlert"),f=a("../chatManagerUtil"),e=a("../../utils/promise"),d=function(){function a(a,b){this.engine=b,this.alertId=a.alertId,this.from=a.from,this.to=a.to,this.group=a.group,this.type=a.type,this.status=a.status,this.lastActiveAt=a.lastActiveAt}return a.prototype._updateCacheWithStatus=function(a){var b;return null!=(b=this.engine.chatManager.dbUtil)?b.openDB().then(function(b){return function(c){var d;return d={alertId:b.alertId,from:b.from,to:b.to,type:b.type,group:b.group,status:a,lastActiveAt:b.lastActiveAt},c.alerts.update(d)}}(this)):void 0},a.prototype.ignore=function(a){var b;return a.alertId=this.alertId,b=f.getPromiseOption(a),this._ignore(b).then(function(b){return function(){var c;return(null!=(c=b.engine.options.chat)?c.enableCache:void 0)?b._updateCacheWithStatus("processed"):"function"==typeof a.onSuccess?a.onSuccess():void 0}}(this)).then(function(){return"function"==typeof a.onSuccess?a.onSuccess():void 0})["catch"](function(b){return"function"==typeof a.onError?a.onError(b):void 0})},a.prototype._ignore=function(a){return this.engine.chatManager.request("engine_chat:alert:ignore",a)},a}(),e.toPromise(d,null,["_updateCacheWithStatus"]),b.exports=d},{"../../utils/promise":32,"../chatManagerUtil":10,debug:38}],9:[function(a,b,c){"use strict";var d,e,f,g,h;h=a("debug")("engine:chat:alerts"),g=a("../chatManagerUtil"),f=a("../../utils/promise"),e=a("./confirmAlert"),d=function(){function a(a){this.engine=a}return a.prototype._loadWithCache=function(a){return this.engine.chatManager.dbUtil.getDataAfterMerged("alerts").then(function(a){return h("load alerts with cache",a),a.newestDatas})},a.prototype.load=function(a){var b,c,d;return b=(null!=(d=this.engine.options.chat)?d.enableCache:void 0)?this._loadWithCache:this._getAlerts,c=g.getPromiseOption(a),b.call(this,c).then(function(b){return function(c){var d,f;return f=function(){var a,b,f;for(f=[],a=0,b=c.length;b>a;a++)d=c[a],"pending"===d.status&&f.push(new e(d,this.engine));return f}.call(b),"function"==typeof a.onSuccess?a.onSuccess(f):void 0}}(this))["catch"](function(b){return"function"==typeof a.onError?a.onError(b):void 0})},a.prototype.formatEventData=function(a){var b;return b=new e(a,this.engine),b._updateCacheWithStatus("pending"),b},a.prototype._getAlerts=function(a){return this.engine.chatManager.request("engine_chat:alert:get",a)},a}(),f.toPromise(d,null,["_loadWithCache","formatEventData"]),b.exports=d},{"../../utils/promise":32,"../chatManagerUtil":10,"./confirmAlert":7,debug:38}],10:[function(a,b,c){"use strict";var d,e;d=a("../utils/promise"),e=a("../protocol"),c._separateOptionsAndHandlers=function(a){var b,c,d,e;d={},b={};for(c in a)e=a[c],"function"==typeof e?b[c]=e:d[c]=e;return[d,b]},c.getPromiseOption=function(a){var b,d,e;return e=c._separateOptionsAndHandlers(a),d=e[0],b=e[1],d}},{"../protocol":29,"../utils/promise":32}],11:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=function(a,b){function c(){this.constructor=a}for(var d in b)n.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},n={}.hasOwnProperty;l=a("debug")("engine:chat:ChatConversation"),g=a("../messages"),k=a("../chatManagerUtil"),f=a("../uploader/imageUploader"),j=a("../uploader/voiceUploader"),i=a("../uploader/videoUploader"),e=a("../../utils/eventEmitter"),h=a("../../utils/promise"),d=function(a){function b(a,b,c){var d;null==a&&(a={}),this.engine=b,null==c&&(c=!1),this.type=a.type,this.target=a.target,this.unreadMessageCount=a.unreadMessageCount,this.lastActiveAt=a.lastActiveAt,this.lastMessage=a.lastMessage,this.extra=a.extra,null==this.unreadMessageCount&&(this.unreadMessageCount=0),c&&(this.isTemporary=!0),this.lastActiveAt||(this.lastActiveAt=(new Date).toISOString()),this.messages=new g(this.engine),(null!=(d=this.engine.options.chat)?d.enableMediaMessage:void 0)&&(this.imageUploader=new f(this.engine),this.voiceUploader=new j(this.engine),this.videoUploader=new i(this.engine))}return m(b,a),b.prototype.loadMessages=function(a){return null==a&&(a={}),a.type=this.type,a.target=this.target,this.messages.load(a)},b.prototype.resetUnread=function(){return this.unreadMessageCount=0,this._resetUnread({type:this.type,target:this.target}),this.updateCache()},b.prototype.updateCache=function(a){var b,c;return null!=a&&(this.unreadMessageCount=a.unreadMessageCount,this.lastActiveAt=a.lastActiveAt,this.lastMessage=a.lastMessage,this.extra=a.extra),(null!=(b=this.engine.options.chat)?b.enableCache:void 0)&&!this.isTemporary&&null!=(c=this.engine.chatManager.dbUtil)?c.openDB().then(function(a){return function(b){var c,d;return c={type:a.type,target:a.target,unreadMessageCount:a.unreadMessageCount,lastMessage:a.lastMessage,lastActiveAt:a.lastActiveAt,extra:a.extra},l("update conversation cache",c),null!=(d=b.conversations)?d.update(c):void 0}}(this)):void 0},b.prototype.sendMessage=function(a){var b,c,d;return d=k._separateOptionsAndHandlers(a),b=d[0],c=d[1],c.type=this.type,c.to=this.target,null==c.content&&(c.content=b),this.messages.send(c)},b.prototype["delete"]=function(a){return this._deleteConversation({type:this.type,target:this.target}).then(function(b){return function(c){var d,e;return b.engine.chatManager.conversations.removeConversationFromBuffer(b.target),(null!=(d=b.engine.options.chat)?d.enableCache:void 0)?null!=(e=b.engine.chatManager.dbUtil)?e.openDB().then(function(c){return c.conversations.remove(b.target),"function"==typeof a.onSuccess?a.onSuccess():void 0}):void 0:"function"==typeof a.onSuccess?a.onSuccess():void 0}}(this))},b.prototype.getImageUploader=function(a){var b;return null==a&&(a={}),(null!=(b=this.engine.options.chat)?b.enableMediaMessage:void 0)?null==a.browseButton||""===a.browseButton?a.onError("BrowseButton does not exist"):this.imageUploader.init({browseButton:a.browseButton,dropElement:a.dropElement,target:this.target,type:this.type,extra:a.extra}).then(function(b){return function(){return"function"==typeof a.onSuccess?a.onSuccess(b.imageUploader):void 0}}(this))["catch"](function(b){return"function"==typeof a.onError?a.onError(b):void 0}):a.onError("You must set enableMediaMessage")},b.prototype.getVoiceUploader=function(a){var b;return null==a&&(a={}),(null!=(b=this.engine.options.chat)?b.enableMediaMessage:void 0)?this.voiceUploader.init({target:this.target,type:this.type,extra:a.extra}).then(function(b){return function(){return"function"==typeof a.onSuccess?a.onSuccess(b.voiceUploader):void 0}}(this))["catch"](function(b){return"function"==typeof a.onError?a.onError(b):void 0}):a.onError("You must set enableMediaMessage")},b.prototype.getVideoUploader=function(a){var b;return null==a&&(a={}),(null!=(b=this.engine.options.chat)?b.enableMediaMessage:void 0)?this.videoUploader.init({target:this.target,type:this.type,extra:a.extra}).then(function(b){return function(){return"function"==typeof a.onSuccess?a.onSuccess(b.videoUploader):void 0}}(this))["catch"](function(b){return"function"==typeof a.onError?a.onError(b):void 0}):a.onError("You must set enableMediaMessage")},b.prototype._deleteConversation=function(a){return this.engine.chatManager.request("engine_chat:conversation:delete",a)},b.prototype._resetUnread=function(a){return this.engine.chatManager.request("engine_chat:conversation:resetUnread",a)},b}(e),h.toPromise(d,null,["updateCache"]),b.exports=d},{"../../utils/eventEmitter":30,"../../utils/promise":32,"../chatManagerUtil":10,"../messages":18,"../uploader/imageUploader":20,"../uploader/videoUploader":22,"../uploader/voiceUploader":23,debug:38}],12:[function(a,b,c){"use strict";var d,e,f,g,h,i;i=a("debug")("engine:chat:conversations"),e=a("./chatConversation"),h=a("../chatManagerUtil"),g=a("../../utils/promise"),f=a("../../utils/eventEmitter"),d=function(){function a(a){this.engine=a,this.initConversationBuffer()}return a.prototype.initConversationBuffer=function(){var a,b,c;b=null!=this._store;for(c in b)a=b[c],a.removeAllListeners();return this._store={}},a.prototype.removeConversationFromBuffer=function(a){var b;return null!=(b=this._store[a])&&b.removeAllListeners(),delete this._store[a]},a.prototype._loadWithCache=function(a){return this.engine.chatManager.dbUtil.getDataAfterMerged("conversations").then(function(a){return function(b){var c,d,e,f,g,h;for(i("load conversations with cache",b),f=b.mergedDatas,d=0,e=f.length;e>d;d++)c=f[d],null!=(g=a._store[c.target])&&(g.isTemporary=!1),null!=(h=a._store[c.target])&&h.updateCache(c);return b.newestDatas.filter(function(a){return!a.isRemoved})}}(this))},a.prototype._loadOneWithoutCache=function(a){var b;return b=h.getPromiseOption(a),this._getConversations(b).then(function(a){return(null!=a?a.length:void 0)>0?a[0]:b})},a.prototype._loadOneWithCache=function(a){var b;return null!=(b=this.engine.chatManager.dbUtil)?b.openDB().then(function(b){return b.conversations.query("target").only(a.target).execute()}).then(function(b){return function(c){var d,e;return c.length>0?c[0]:(d=null,e=h.getPromiseOption(a),b._getConversations(e).then(function(a){var b;return(null!=a?a.length:void 0)>0?(b=a[0],b.isNew=!0,b):(b=e,b.isTemporary=!0,b)}))}}(this)):void 0},a.prototype.load=function(a){var b,c,d;return null==a&&(a={}),b=(null!=(d=this.engine.options.chat)?d.enableCache:void 0)?this._loadWithCache:this._getConversations,c=h.getPromiseOption(a),b.call(this,c).then(function(b){return function(c){var d,f,g,h,i,j;for(g=[],h=0,i=c.length;i>h;h++)f=c[h],null==(d=b._store)[j=f.target]&&(d[j]=new e(f,b.engine)),g.push(b._store[f.target]);return"function"==typeof a.onSuccess?a.onSuccess(g):void 0}}(this))["catch"](function(b){return"function"==typeof a.onError?a.onError(b):void 0})},a.prototype.loadOne=function(a){var b,c,d;return a.target?null!=this._store[a.target]?a.onSuccess(this._store[a.target]):(b=(null!=(d=this.engine.options.chat)?d.enableCache:void 0)?this._loadOneWithCache:this._loadOneWithoutCache,c=h.getPromiseOption(a),null!=b?b.call(this,c).then(function(b){return function(c){var d,f;return null!=c?(null==(d=b._store)[f=c.target]&&(d[f]=new e(c,b.engine,c.isTemporary)),c.isNew&&b._store[c.target].updateCache(),"function"==typeof a.onSuccess?a.onSuccess(b._store[c.target]):void 0):a.onSuccess()}}(this))["catch"](function(b){return"function"==typeof a.onError?a.onError(b):void 0}):void 0):a.onError("target is required")},a.prototype.handleEvent=function(a){var b,c,d;switch(i("Conversation handleEvent dispatcher",a),a.name){case"message:new":if(b="singleChat"===a.data.type?this._store[a.data.from]:this._store[a.data.to],!b)return;return b.lastMessage=a.data,b.unreadMessageCount++,b.lastActiveAt=a.data.createdAt,b.updateCache(),(null!=(c=this.engine.options.chat)?c.enableCache:void 0)?null!=(d=this.engine.chatManager.dbUtil)?d.openDB().then(function(c){var d;return d=a.data,d.id=d.from+d.to+d.messageId,d.target=b.target,c.messages.update(d).then(function(){return b.trigger(a.name,a.data)})}):void 0:b.trigger(a.name,a.data)}},a.prototype._getConversations=function(a){return this.engine.chatManager.request("engine_chat:conversation:get",a)},a}(),g.toPromise(d,["load","loadOne","_getConversations"]),b.exports=d},{"../../utils/eventEmitter":30,"../../utils/promise":32,"../chatManagerUtil":10,"./chatConversation":11,debug:38}],13:[function(a,b,c){"use strict";var d,e,f,g,h,i;g=a("debug")("engine:chat:dbUtil"),h=a("../utils/requester/loadJS"),e=a("../utils/promise"),i={conversations:{key:{keyPath:"target"},indexes:{lastActiveAt:{},target:{}}},messages:{key:{keyPath:"id"},indexes:{messageId:{},createdAt:{},from:{},to:{},type:{},target:{}}},groups:{key:{keyPath:"groupId"},indexes:{lastActiveAt:{},groupId:{},isRemoved:{}}},alerts:{key:{keyPath:"alertId"},indexes:{lastActiveAt:{},from:{},group:{},alertId:{},status:{},to:{},type:{}}},tmpMessages:{key:{keyPath:"id",autoIncrement:!0},indexes:{messageId:{},createdAt:{},from:{},to:{},type:{},target:{}}}},f=2,d=function(){function a(a){this.engine=a}return a.prototype.handelDbException=function(a,b){var c,d;return console.warn(a),null!=(c=this.server)&&"function"==typeof c.close&&c.close(),this.server=null,null!=b&&g(b),null!=(d=this.engine.options.chat)?d.enableCache=!1:void 0},a.prototype.initLocalDB=function(){return this.openDB()["catch"](function(a){return function(b){return a.handelDbException("Your browser does not support local storage",b),e.resolve()}}(this))},a.prototype.openDB=function(){var a,b,c,d;if(!(null!=(b=this.engine.options.chat)?b.enableCache:void 0))return e.reject("You must set enableCache");if(a=this.engine.chatManager.user.userId,!a)return e.reject("You must login firstly.");if("chatManagerDB-"+a===this.dbName){if(this.server)return e.resolve(this.server)}else null!=(c=this.server)&&c.close();return g("Switch db",this.dbName+(" -> chatManagerDB-"+a)),this.dbName="chatManagerDB-"+a,d=this,new e(function(a,b){return h.require("enableCache",d.engine.options.basePath).then(function(){return db.open({server:d.dbName,version:f,schema:i})}).then(function(c){return null==c.conversations?(d.handelDbException("Can not open db, you can try again after cleaned cache"),b()):(d.server=c,a(c))})["catch"](function(a){return d.handelDbException("Your browser does not support local storage",a),b(a)})})},a.prototype.clearCache=function(){var a,b,c,d,e,f,h;if((null!=(a=this.engine)&&null!=(b=a.options.chat)?b.enableCache:void 0)&&this.server)return g("clean cache",this.dbName),null!=(c=this.server.messages)&&c.clear(),null!=(d=this.server.conversations)&&d.clear(),null!=(e=this.server.groups)&&e.clear(),null!=(f=this.server.alerts)&&f.clear(),null!=(h=this.server)&&"function"==typeof h.close&&h.close(),this.server=null,"undefined"!=typeof indexedDB&&null!==indexedDB?indexedDB.deleteDatabase(this.dbName):void 0},a.prototype.getRemoteData=function(a,b){var c,d;return null==b&&(b={}),c={conversations:"engine_chat:conversation:get",alerts:"engine_chat:alert:get",groups:"engine_chat:group:get",messages:"engine_chat:message:get"},c[a]?("message"===a&&(d=!0),new e(function(e){return function(f,g){return b.onSuccess=function(b){return"messages"===a&&(b.id=b.from+b.to+b.messageId),f(b)},b.onError=function(a){return g(a)},e.engine.chatManager.request(c[a],b,d)}}(this))):e.resolve([])},a.prototype.match=function(a){return function(b){var c,d;for(c in a)if(d=a[c],"lastActiveAt"!==c&&null!=b[c]&&b[c]!==d)return!1;return!0}},a.prototype.getDataAfterMerged=function(a,b){var c;return null==b&&(b={}),c={},this.openDB().then(function(d){return function(e){return c.db=e,c.db[a].query("lastActiveAt").filter(d.match(b)).desc().execute()}}(this)).then(function(d){return function(e){var f;return null==e&&(e=[]),c.data=e,null!=(null!=(f=e[0])?f.lastActiveAt:void 0)&&(b.lastActiveAt=e[0].lastActiveAt),d.getRemoteData(a,b)}}(this)).then(function(b){var d,f,g,h;for(null==b&&(b=[]),c.remoteDatas=b,g=[],d=0,f=b.length;f>d;d++)h=b[d],g.push(c.db[a].update(h));return e.all(g)}).then(function(d){return function(){return c.db[a].query("lastActiveAt").filter(d.match(b)).desc().execute()}}(this)).then(function(a){return null==a&&(a=[]),{newestDatas:a,mergedDatas:c.remoteDatas}})},a}(),b.exports=d},{"../utils/promise":32,"../utils/requester/loadJS":35,debug:38}],14:[function(a,b,c){"use strict";var d,e,f,g,h;h=a("debug")("engine:chat:group"),f=a("../users"),g=a("../chatManagerUtil"),e=a("../../utils/promise"),d=function(){function a(a,b){this.engine=b,this.groupId=a.groupId,this.owner=a.owner,this.isPublic=a.isPublic,this.userCanInvite=a.userCanInvite,this.userCount=a.userCount,this.userCountLimit=a.userCountLimit,this.isRemoved=a.isRemoved,this.lastActiveAt=a.lastActiveAt,this.users=new f(this.engine)}return a.prototype.loadUsers=function(a){return a.groupId=this.groupId,this.users.loadGroupUsers(a)},a.prototype.inviteUsers=function(a){return a.groupId=this.groupId,this._inviteUsers(a)},a.prototype.removeUsers=function(a){return a.groupId=this.groupId,this._removeUsers(a)},a.prototype.leave=function(a){var b;return null==a&&(a={}),a.groupId=this.groupId,b=g.getPromiseOption(a),this._leaveGroup(b).then(function(b){return function(){var c,d;return b.engine.chatManager.conversations.removeConversationFromBuffer(b.groupId),(null!=(c=b.engine.options.chat)?c.enableCache:void 0)?null!=(d=b.engine.chatManager.dbUtil)?d.openDB().then(function(a){return e.all([a.conversations.remove(b.groupId),a.groups.remove(b.groupId)])}).then(function(){return"function"==typeof a.onSuccess?a.onSuccess():void 0})["catch"](function(){return"function"==typeof a.Error?a.Error():void 0}):void 0:"function"==typeof a.onSuccess?a.onSuccess():void 0}}(this))["catch"](function(b){return"function"==typeof a.Error?a.Error(b):void 0})},a.prototype._inviteUsers=function(a){return this.engine.chatManager.request("engine_chat:group:joinInvitation:send",a)},a.prototype._removeUsers=function(a){return this.engine.chatManager.request("engine_chat:group:removeUsers",a)},a.prototype._leaveGroup=function(a){return this.engine.chatManager.request("engine_chat:group:leave",a)},a}(),e.toPromise(d,null,["updateCache"]),b.exports=d},{"../../utils/promise":32,"../chatManagerUtil":10,"../users":24,debug:38}],15:[function(a,b,c){"use strict";var d,e,f,g,h;h=a("debug")("engine:chat:groups"),g=a("../chatManagerUtil"),e=a("./chatGroup"),f=a("../../utils/promise"),d=function(){function a(a){this.engine=a}return a.prototype._loadWithCache=function(a){var b;return b={},this.engine.chatManager.dbUtil.getDataAfterMerged("groups",a).then(function(a){return function(c){var d;return h("load groups with cache",c),b.data=c,null!=(d=a.engine.chatManager.dbUtil)?d.openDB():void 0}}(this)).then(function(a){var c,d,e,f,g;for(d=b.data.newestDatas,g=d.slice(1),e=0,f=g.length;f>e;e++)c=g[e],c.isRemoved&&a.groups.remove(c.groupId);return d.filter(function(a){return!a.isRemoved})})},a.prototype.load=function(a){var b,c,d;return null==a&&(a={}),b=(null!=(d=this.engine.options.chat)?d.enableCache:void 0)?this._loadWithCache:this._getGroups,c=g.getPromiseOption(a),b.call(this,c).then(function(b){return function(c){var d,f;return f=function(){var a,b,f;for(f=[],a=0,b=c.length;b>a;a++)d=c[a],f.push(new e(d,this.engine));return f}.call(b),"function"==typeof a.onSuccess?a.onSuccess(f):void 0}}(this))["catch"](function(b){return"function"==typeof a.onError?a.onError(b):void 0})},a.prototype.create=function(a){var b;return b=g.getPromiseOption(a),this._createGroup(b).then(function(a){return function(b){return a._getGroups({groupId:b.groupId})}}(this)).then(function(b){return function(c){var d,f,g;if(("undefined"!=typeof grups&&null!==grups?grups.length:void 0)<0)throw new Error("create group failed");return(null!=(f=b.engine.options.chat)?f.enableCache:void 0)&&null!=(g=b.engine.chatManager.dbUtil)&&g.openDB().then(function(a){var b;return null!=(b=a.groups)?b.update(c[0]):void 0}),d=new e(c[0]),"function"==typeof a.onSuccess?a.onSuccess(d):void 0}}(this))["catch"](function(b){return"function"==typeof a.onError?a.onError(b):void 0})},a.prototype._getGroups=function(a){return this.engine.chatManager.request("engine_chat:group:get",a)},a.prototype._createGroup=function(a){return this.engine.chatManager.request("engine_chat:group:create",a)},a}(),f.toPromise(d,null,["_loadWithCache"]),b.exports=d},{"../../utils/promise":32,"../chatManagerUtil":10,"./chatGroup":14,debug:38}],16:[function(a,b,c){"use strict";var d,e,f,g;e=a("../../utils/promise"),f=a("debug")("engine:chat:locationHelper"),d=function(){function a(){}return a.prototype.getLocation=function(a){var b,c,d;return("undefined"!=typeof navigator&&null!==navigator?navigator.geolocation:void 0)?(d=function(b){var c;return c={lat:b.coords.latitude,lng:b.coords.longitude},a.onSuccess(c)},c=function(b){return a.onError(b)},b={enableHighAccuracy:!0,timeout:5e3,maximumAge:3e4},navigator.geolocation.getCurrentPosition(d,c,b)):a.onError("Geolocation is not supported by this browser.")},a}(),e.toPromise(d,["getLocation"]),g=new d,b.exports=g},{"../../utils/promise":32,debug:38}],17:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n,o,p=function(a,b){return function(){return a.apply(b,arguments)}},q=function(a,b){function c(){this.constructor=a}for(var d in b)r.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},r={}.hasOwnProperty;n=a("debug")("engine:chat:chatManager"),l=a("../protocol"),f=a("./conversations"),i=a("./groups"),d=a("./alerts"),k=a("../utils/promise"),m=a("./chatManagerUtil"),g=a("./dbUtil"),j=a("./helpers/locationHelper"),o=a("../utils/requester/loadJS"),h=a("../utils/eventEmitter"),e=function(a){function b(a){var b;this.engine=a,this.request=p(this.request,this),this._handleOptions=p(this._handleOptions,this),this._handleOptions(),this._loginOptions=null,this.user=null,this.state="initialized",this.noConnectionOperations=[],this.conversations=new f(this.engine),this.groups=new i(this.engine),this.alerts=new d(this.engine),this.locationHelper=j,this.supportOffline=(null!=(b=this.engine.options)?b.supportOffline:void 0)||!1}return q(b,a),b.prototype._handleOptions=function(){var a,b,c,d,e;if(n("handle options",this.engine.options),(null!=(c=this.engine.options)?c.chat:void 0)&&(b=[],this.engine.options.chat&&"undefined"!=typeof window&&null!==window)){d=this.engine.options.chat;for(a in d)e=d[a],this.engine.options.chat[a]&&b.push(o.require(a,this.engine.options.basePath));return k.all(b).then(function(a){return n("load extension over",a),a})}},b.prototype.login=function(a){var b;return null==a&&(a={}),this.state="loggingIn",this._loginOptions=a,"connected"===this.engine.connection.state?(a.authData||(a.authData=null!=(b=this.engine.options)?b.authData:void 0),this.engine.authorizer.authorize(a,{chatLogin:!0},function(a){return function(b,c){var d;if(b)return a.state="failed",a.trigger("login:failed",b);d=a.user;try{a.user=JSON.parse(c.userData)}catch(e){}return a.engine.connection.sendEvent("engine_chat:user:login",c,function(b,c){var e,f,h,i;if(b){if(b.code===l.responseErrors.noConnection)return;return n("login error",b),a.state="failed",a.trigger("login:failed",b)}for(e in c)i=c[e],a.user[e]=i;return a.state="loggedIn",(null!=d?d.userId:void 0)===(null!=(f=a.user)?f.userId:void 0)?a.handleNoConnectionOperations():null!=d&&a.handleNoConnectionOperations(!0),(null!=(h=a.engine.options.chat)?h.enableCache:void 0)?(null==a.dbUtil&&(a.dbUtil=new g(a.engine)),a.dbUtil.initLocalDB().then(function(){return a.trigger("login:succeeded",c)})):a.trigger("login:succeeded"),n("login succeeded",c)})}}(this))):void 0},b.prototype.autoLogin=function(){return this._loginOptions?this.login(this._loginOptions):void 0},b.prototype.logout=function(a){var b,c,d;return this._loginOptions=null,d=m._separateOptionsAndHandlers(a),a=d[0],c=d[1],b=this.engine.connection.sendEvent("engine_chat:user:logout",function(a){return function(d){return d?d.code===l.responseErrors.noConnection.code?(a.bufferNoConnectionOperations("engine_chat:user:logout",null,b),a.state="loggedOut","function"==typeof c.onSuccess?c.onSuccess():void 0):(n("logout error",d),"function"==typeof c.onError?c.onError(d):void 0):(a.handleNoConnectionOperations(!0),a.state="loggedOut",a.conversations.initConversationBuffer(),a.user=null,n("logout succeeded"),"function"==typeof c.onSuccess?c.onSuccess():void 0)}}(this))},b.prototype.handleEvent=function(a){
2 | var b;switch(b=a.name.replace("engine_chat:",""),a.name=b,a.data=this.formatEventData(a),this.trigger(b,a.data),a.name){case"message:new":return this.conversations.handleEvent(a),this.engine.connection.sendResponseEvent(a.id);case"alert:new":return this.engine.connection.sendResponseEvent(a.id)}},b.prototype.formatEventData=function(a){return"alert:new"===a.name?this.alerts.formatEventData(a.data):a.data},b.prototype.bufferNoConnectionOperations=function(a,b,c){var d,e;return c&&(null!=(e=this.user)?e.userId:void 0)?(null==this.noConnectionOperations&&(this.noConnectionOperations=[]),d={name:a,data:b,callback:c},n("buffer no connection operations",d),"engine_chat:message:send"!==a&&(d.timer=setTimeout(function(){var a;return a=l.responseErrors.requestTimeout,a.isFailed=!0,c(a),d.isTimeout=!0},6e4)),this.noConnectionOperations.push(d)):void 0},b.prototype.handleNoConnectionOperations=function(a){var b,c,d;if(!((null!=(d=this.noConnectionOperations)?d.length:void 0)<1&&this.handlingNoConnectionOperations)||a){for(this.handlingNoConnectionOperations=!0;c=this.noConnectionOperations.shift();)c.isTimeout||(null!=c.timer&&clearTimeout(c.timer),a?(b=l.responseErrors.noConnection,b.isFailed=!0,c.callback(b)):this.engine.connection.sendEvent(c.name,c.data,c.callback));return this.handlingNoConnectionOperations=!1}},b.prototype.clearCache=function(){var a,b;return(null!=(a=this.engine.options.chat)?a.enableCache:void 0)&&null!=(b=this.dbUtil)?b.clearCache():void 0},b.prototype.request=function(a,b,c){var d,e,f;return f=m._separateOptionsAndHandlers(b),b=f[0],e=f[1],"loggedIn"!==this.state?"function"==typeof e.onError?e.onError(l.responseErrors.unauthorized):void 0:(d=function(c){return function(f,g){var h;return f?f.code===l.responseErrors.noConnection.code&&!f.isFailed&&c.supportOffline?-1!==a.indexOf("get")&&(null!=(h=c.engine.options.chat)?h.enableCache:void 0)?e.onSuccess([]):c.bufferNoConnectionOperations(a,b,d):"function"==typeof e.onError?e.onError(f):void 0:"function"==typeof e.onSuccess?e.onSuccess(g):void 0}}(this),c&&(d.needSendAck=!0),this.engine.connection.sendEvent(a,b,d))},b.prototype.clearAllCache=function(){return n("clean all cache"),"undefined"!=typeof indexedDB&&null!==indexedDB&&"function"==typeof indexedDB.webkitGetDatabaseNames?indexedDB.webkitGetDatabaseNames().onsuccess=function(a,b){var c,d,e,f,g;for(f=a.target.result,g=[],c=0,d=f.length;d>c;c++)e=f[c],n("clean cache",e),e.indexOf(!1)?g.push("undefined"!=typeof indexedDB&&null!==indexedDB?indexedDB.deleteDatabase(e):void 0):g.push(void 0);return g}:void 0},b}(h),k.toPromise(e,["logout"]),b.exports=e},{"../protocol":29,"../utils/eventEmitter":30,"../utils/promise":32,"../utils/requester/loadJS":35,"./alerts":9,"./chatManagerUtil":10,"./conversations":12,"./dbUtil":13,"./groups":15,"./helpers/locationHelper":16,debug:38}],18:[function(a,b,c){"use strict";var d,e,f,g,h;h=a("debug")("engine:chat:messages"),g=a("../chatManagerUtil"),e=a("../../utils/promise"),f=a("./tmpMessage"),d=function(){function a(a){this.engine=a}return a.prototype._loadNewestMessages=function(a){var b,c,d;return h("load newest messages",a),b=a.limit||20,d={},null!=(c=this.engine.chatManager.dbUtil)?c.openDB().then(function(b){return function(c){return d.db=c,d.db.messages.query("messageId").filter(b.engine.chatManager.dbUtil.match({target:a.target,type:a.type})).desc().execute()}}(this)).then(function(b){return function(c){var e,f;return null==c&&(c=[]),h("get last local message",c[0]),e=(null!=(f=c[0])?f.messageId:void 0)+1||0,d.messagesResult=c,b._getMessages({type:a.type,target:a.target,endMessageId:e})}}(this)).then(function(c){return function(f){var g,i,j,k,l;for(h("get newest messages",f),g=0,i=f.length;i>g;g++)j=f[g],j.isNew=!0;return k=f.concat(d.messagesResult),l=c._loadMissingMessageBlocksPromises(k,a),e.all(l).then(function(a){var c,d,e,f,g;for(h("missing messages blocks:",a),c=0,e=a.length;e>c;c++)if(g=a[c],null!=g)for(d=0,f=g.length;f>d;d++)j=g[d],j.isNew=!0,k.push(j);return k.slice(0,+b+1||9e9)})}}(this)):void 0},a.prototype._loadMissingMessageBlocksPromises=function(a,b){var c,d;if(d=[],0===a.length)return d.push(this._getMessages({type:b.type,target:b.target,startMessageId:b.startMessageId,endMessageId:b.endMessageId,limit:b.limit||20})),d;for(b.startMessageId>a[0].messageId&&d.push(this._getMessages({type:b.type,target:b.target,startMessageId:b.startMessageId,endMessageId:a[0].messageId+1,limit:b.startMessageId-a[0].messageId})),b.endMessageIdd;d++)g=a[d],g.isNew&&(g.target=b,g.id=g.from+g.to+g.messageId,h.push(c.messages.update(g)));return e.all(h)}):void 0},a.prototype._loadWithCache=function(a){var b,c;return null==a.startMessageId||null==a.endMessageId?this._loadNewestMessages(a):(b=a.limit||20,a.startMessageId||(a.startMessageId=a.endMessageId+b),a.endMessageId||(a.endMessageId=a.startMessageId-b),h("load with cache",a),null!=(c=this.engine.chatManager.dbUtil)?c.openDB().then(function(b){return function(c){return c.messages.query("messageId").bound(a.endMessageId,a.startMessageId).filter(b.engine.chatManager.dbUtil.match({target:a.target,type:a.type})).desc().execute()}}(this)).then(function(c){return function(d){var f;return h("local load",d),b=a.startMessageId-a.endMessageId+1,d.length===b?e.resolve(d):(f=c._loadMissingMessageBlocksPromises(d,a),e.all(f).then(function(a){var b,c,e,f,g,i;for(h("missing messages blocks:",a),b=0,e=a.length;e>b;b++)if(i=a[b],null!=i)for(c=0,f=i.length;f>c;c++)g=i[c],g.isNew=!0,d.push(g);return d}))}}(this)):void 0)},a.prototype.load=function(a){var b,c,d,i;return b=(null!=(i=this.engine.options.chat)?i.enableCache:void 0)?this._loadWithCache:this._getMessages,d=g.getPromiseOption(a),null==d.to&&(d.to=d.target),c=a.limit||20,b.call(this,d).then(function(b){return function(g){var i;return(null!=(i=b.engine.options.chat)?i.enableCache:void 0)?b._save(g,d.target).then(function(){var a;return null!=(a=b.engine.chatManager.dbUtil)?a.openDB():void 0}).then(function(c){return b.engine.options.supportOffline?c.tmpMessages.query("messageId").filter(b.engine.chatManager.dbUtil.match({target:a.target,type:a.type})).desc().execute():e.resolve([])}).then(function(d){var e,i,j,k,l,m,n;for(h("tmp messages",d),e=0,j=d.length;j>e;e++)m=d[e],n=new f(b.engine,m),"sending"===n.state&&n.retrySendMessage(),g.push(n);for(g.sort(function(a,b){var c;return c=b.messageId-a.messageId,0===c?(null!=b?b.id:void 0)-(null!=a?a.id:void 0):c}),i=0,k=g.length;k>i;i++)l=g[i],null==l.state&&(l.state="succeed");return"function"==typeof a.onSuccess?a.onSuccess(g.slice(0,+c+1||9e9)):void 0}):"function"==typeof a.onSuccess?a.onSuccess(g.slice(0,+c+1||9e9)):void 0}}(this))["catch"](function(b){return"function"==typeof a.onError?a.onError(b):void 0})},a.prototype.send=function(a){var b,c,d,e,i;return d=g.getPromiseOption(a),b=d,b.from=this.engine.chatManager.user.userId,c=void 0,(null!=(e=this.engine.options.chat)?e.enableCache:void 0)&&this.engine.options.supportOffline?(i=new f(this.engine,b),c=i.save().then(function(a){return function(){return a._sendMessage(d)}}(this))):c=this._sendMessage(d),c.then(function(c){return function(d){var e,f;return b.messageId=d.messageId,b.id=b.from+b.to+d.messageId,null!=d.content?b.content=d.content:b.content=a.content,(null!=(e=c.engine.options.chat)?e.enableCache:void 0)?null!=(f=c.engine.chatManager.dbUtil)?f.openDB().then(function(d){return c.engine.options.supportOffline?i.remove().then(function(){return h("removed tmpMessage",i.id),b.target=a.to,d.messages.update(b),"function"==typeof a.onSuccess?a.onSuccess(b):void 0}):(b.target=a.to,d.messages.update(b),"function"==typeof a.onSuccess?a.onSuccess(b):void 0)}):void 0:"function"==typeof a.onSuccess?a.onSuccess(b):void 0}}(this))["catch"](function(b){return function(c){var d,e;return(null!=(d=b.engine.options.chat)?d.enableCache:void 0)&&b.engine.options.supportOffline?(i.changState("failed"),null!=(e=b.engine.chatManager.dbUtil)?e.openDB().then(function(a){return a.tmpMessages.update(i.toJSON())}).then(function(){return null!=a&&"function"==typeof a.onError?a.onError(c):void 0}):void 0):null!=a&&"function"==typeof a.onError?a.onError(c):void 0}}(this))},a.prototype._sendMessage=function(a){return this.engine.chatManager.request("engine_chat:message:send",a)},a.prototype._getMessages=function(a){return this.engine.chatManager.request("engine_chat:message:get",a,!0)},a}(),e.toPromise(d,["send","load","_getMessages","_sendMessage"]),b.exports=d},{"../../utils/promise":32,"../chatManagerUtil":10,"./tmpMessage":19,debug:38}],19:[function(a,b,c){"use strict";var d,e,f=function(a,b){return function(){return a.apply(b,arguments)}},g=function(a,b){function c(){this.constructor=a}for(var d in b)h.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},h={}.hasOwnProperty;d=a("../../utils/eventEmitter"),e=function(b){function c(a,b){this.engine=a,null==b&&(b={}),this.changState=f(this.changState,this),this.messageId=b.messageId,this.createdAt=b.createdAt,this.from=b.from,this.to=b.to,this.type=b.type,this.content=b.content,this.state=b.state,this.target=b.target,this.id=b.id,null==this.state&&(this.state="sending"),null==this.target&&(this.target=this.to)}return g(c,b),c.prototype.save=function(){var a;return null!=(a=this.engine.chatManager.dbUtil)?a.openDB().then(function(a){return function(b){return null!=a.messageId?b.tmpMessages.add(a.toJSON()):b.messages.query("messageId").filter(a.engine.chatManager.dbUtil.match({target:a.target,type:a.type})).desc().execute().then(function(c){var d;return null==c&&(c=[]),a.messageId=(null!=(d=c[0])?d.messageId:void 0)||0,b.tmpMessages.add(a.toJSON())})}}(this)).then(function(a){return function(b){return a.id=b[0].id,a.toJSON()}}(this)):void 0},c.prototype.changState=function(a){var b,c,d;if("string"==typeof a)return c=[this.state,a],b=c[0],this.state=c[1],d={previous:b,current:this.state},this.trigger("state:changed",d)},c.prototype.toJSON=function(){var a;return a={messageId:this.messageId,createdAt:this.createdAt,from:this.from,to:this.to,type:this.type,state:this.state,content:this.content,target:this.target},this.id&&(a.id=this.id),a},c.prototype.remove=function(){var a;if(this.id)return null!=(a=this.engine.chatManager.dbUtil)?a.openDB().then(function(a){return function(b){return b.tmpMessages.remove(a.id)}}(this)):void 0},c.prototype.retrySendMessage=function(){return"succeeded"!==this.state?this.remove().then(function(b){return function(){var c,d;return c=a("../messages"),d=new c(b.engine),d.send({target:b.to,type:b.type,content:b.content,from:b.from,to:b.to})}}(this)).then(function(a){return function(b){return a.messageId=b.messageId,a.changState("succeeded"),a.toJSON()}}(this))["catch"](function(a){return function(){return a.changState("failed")}}(this)):void 0},c}(d),b.exports=e},{"../../utils/eventEmitter":30,"../messages":18}],20:[function(a,b,c){"use strict";var d,e,f,g=function(a,b){function c(){this.constructor=a}for(var d in b)h.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},h={}.hasOwnProperty;f=a("debug")("engine:chat:ChatImageUploader"),e=a("./uploader"),d=function(a){function b(a){this.engine=a,b.__super__.constructor.call(this,this.engine)}return g(b,a),b.prototype.init=function(a){return a.messageType="image",b.__super__.init.call(this,a)},b}(e),b.exports=d},{"./uploader":21,debug:38}],21:[function(a,b,c){"use strict";var d,e,f,g,h,i,j=function(a,b){return function(){return a.apply(b,arguments)}},k=function(a,b){function c(){this.constructor=a}for(var d in b)l.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},l={}.hasOwnProperty;h=a("debug")("engine:chat:ChatUploader"),e=a("../../utils/eventEmitter"),f=a("../messages"),i=a("../../utils/requester/loadJS"),g=a("../../utils/promise"),d=function(a){function b(a){this.engine=a,this._requestPermission=j(this._requestPermission,this),this._changstate=j(this._changstate,this),this.init=j(this.init,this),this._uploader={},this.state="initialized",this.messages=new f(this.engine)}return k(b,a),b.prototype.init=function(a){var b,c,d,e;return h("uploader init",a),(null!=(d=this.engine.options.chat)?d.enableMediaMessage:void 0)?(e=this,b=null!=a.browseButton?a.browseButton:"undefined"!=typeof document&&null!==document?document.createElement("input"):void 0,i.require("enableMediaMessage",this.engine.options.basePath).then(function(){return e._uploader=Qiniu.uploader({runtimes:"html5,flash,html4",browse_button:b,uptoken:e.engine.chatManager.user.uploadToken,domain:"domain",chunk_size:"4mb",dragdrop:!0,drop_element:a.dropElement,max_file_size:"100mb",save_key:!0,auto_start:!0,x_vars:{targetId:a.target},init:{FileUploaded:function(b,c,d){var f;switch(h("file uploaded, wait to send",d),e.trigger("upload:done",c,d),d=JSON.parse(d),f={content:{type:a.messageType,file:{key:d.key,name:d.fname,size:d.fsize,etag:d.etag,mimeType:d.mimeType}},type:a.type,to:a.target,from:e.engine.chatManager.user.userId},a.messageType){case"image":f.content.file.width=d.imageInfo.width,f.content.file.height=d.imageInfo.height;break;case"voice":f.content.file.duration=d.avinfo.audio.duration;break;case"video":f.content.file.width=d.avinfo.video.width,f.content.file.height=d.avinfo.video.height,f.content.file.duration=d.avinfo.video.duration||d.avinfo.format.duration}return e.trigger("message:sending",f),a.extra&&(f.extra=a.extra),e.messages.send(f).then(function(a){return a.createdAt=(new Date).toISOString(),a.state="sent",e.trigger("message:sent",a)})["catch"](function(a){return h("send message failed",a),e.trigger("message:sendFailed",a)})},Error:function(a,b,c){return h("init uploader failed",b,c),e.trigger("upload:error",b,c)}}}),e._uploader.bind("StateChanged",function(a){switch(a.state){case 1:return e._changstate("uploaded");case 2:return e._changstate("uploading")}})})["catch"](function(a){return h("Init uploader failed",a),e._changstate("failed"),e.trigger("failed",a)})):(c="if you want use getVideoUploader you must enableMediaMessage",this._changstate("failed"),this.trigger("failed",c),g.reject(c))},b.prototype._changstate=function(a){var b,c,d;if("string"==typeof a)return c=[this.state,a],b=c[0],this.state=c[1],d={previous:b,current:this.state},h("state changed",d),this.trigger("state:changed",d)},b.prototype.destroy=function(){var a,b,c;return(null!=(a=this.mediaConstraints)?a.video:void 0)&&(null!=(b=this.stream)&&b.stop(),this.recordRTC=null),null!=(c=this._uploader)&&c.destroy(),this.unbind()},b.prototype._requestPermission=function(a,b,c){var d,e,f,g;if(this.mediaConstraints){this._changstate("initializing"),g=function(d){return function(e){return d._changstate("initialized"),d.stream=e,d.recordRTC=RecordRTC(e,a),null!=d[b]?d[b](c):void 0}}(this),f=function(a){return function(b){return a._changstate("failed"),a.trigger("failed",b),console.warn("Can not open media!!!",b)}}(this);try{return navigator.getUserMedia(this.mediaConstraints,g,f)}catch(e){return d=e,this._onMediaError("Your browser does not support getUserMedia")}}},b}(e),b.exports=d},{"../../utils/eventEmitter":30,"../../utils/promise":32,"../../utils/requester/loadJS":35,"../messages":18,debug:38}],22:[function(a,b,c){"use strict";var d,e,f,g=function(a,b){return function(){return a.apply(b,arguments)}},h=function(a,b){function c(){this.constructor=a}for(var d in b)i.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},i={}.hasOwnProperty;f=a("debug")("engine:chat:ChatVideoUploader"),d=a("./uploader"),e=function(a){function b(a){this.engine=a,this.getRealTimeData=g(this.getRealTimeData,this),this.send=g(this.send,this),this._stopHandler=g(this._stopHandler,this),this.stopRecord=g(this.stopRecord,this),this.startRecord=g(this.startRecord,this),this.requestPermission=g(this.requestPermission,this),b.__super__.constructor.call(this,this.engine),this.mediaConstraints={video:!0},this.isChrome="undefined"!=typeof navigator.webkitGetUserMedia,this.isChrome||(this.mediaConstraints.audio=!0)}return h(b,a),b.prototype.requestPermission=function(a,b){var c;return c={disableLogs:!0,type:"video",video:{width:320,height:240},canvas:{width:320,height:240}},this.isChrome||(c={disableLogs:!0}),this._requestPermission(c,a,b)},b.prototype.init=function(a){return a.messageType="video",b.__super__.init.call(this,a)},b.prototype.startRecord=function(a){var b,c;if("recording"!==(b=this.state)&&"uploading"!==b)return this.recordRTC?(this._changstate("recording"),this.trigger("record:started"),this.recordRTC.blob=null,this.duration=null,this.recordRTC.startRecording(),c=URL.createObjectURL(this.stream),a.src=c,a.autoplay=!0,this.startTime=(new Date).getTime(),this.recordTimer=setTimeout(function(a){return function(){return a.stopRecord()}}(this),6e4)):this.requestPermission("startRecord",a)},b.prototype.stopRecord=function(){return"recording"!==this.state?console.warn("You have to perform when you record."):this.recordRTC?(null!=this.recordTimer&&clearTimeout(this.recordTimer),this.recordRTC.stopRecording(function(a){return function(b){return a._changstate("recorded"),a.tmpVideoURL=b,a._stopHandler(b)}}(this))):this.requestPermission("stopRecord")},b.prototype._stopHandler=function(a){return this.duration||(this.duration=(new Date).getTime()-this.startTime),this.trigger("record:stop",a,this.duration)},b.prototype.send=function(){return"uploading"===this.state?console.warn("Please wait for the upload."):this.recordRTC?(null!=this.recordTimer&&clearTimeout(this.recordTimer),"recorded"===this.state?(this._uploader.addFile(this.recordRTC.getBlob()),void this._stopHandler(this.tmpVideoURL)):this.recordRTC.stopRecording(function(a){return function(b){var c;return c=a.recordRTC.getBlob(),null!=c&&a._uploader.addFile(c),a._stopHandler(b)}}(this))):this.requestPermission()},b.prototype.getRealTimeData=function(a){var b;return"recording"===this.state?console.warn("You must stop recording."):this.recordRTC?(this.recordRTC.startRecording(),b=URL.createObjectURL(this.stream),a.src=b,a.autoplay=!0):this.requestPermission("getRealTimeData",a)},b}(d),b.exports=e},{"./uploader":21,debug:38}],23:[function(a,b,c){"use strict";var d,e,f,g=function(a,b){return function(){return a.apply(b,arguments)}},h=function(a,b){function c(){this.constructor=a}for(var d in b)i.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},i={}.hasOwnProperty;f=a("debug")("engine:chat:ChatVoiceUploader"),d=a("./uploader"),e=function(a){function b(a){this.engine=a,this.send=g(this.send,this),this._stopHandler=g(this._stopHandler,this),this.stopRecord=g(this.stopRecord,this),this.startRecord=g(this.startRecord,this),this.requestPermission=g(this.requestPermission,this),b.__super__.constructor.call(this,this.engine),this.mediaConstraints={audio:!0},this.isChrome="undefined"!=typeof navigator.webkitGetUserMedia}return h(b,a),b.prototype.requestPermission=function(a,b){var c;return c={disableLogs:!0},this.isChrome&&(c.compression=8),this._requestPermission(c,a,b)},b.prototype.init=function(a){return a.messageType="voice",b.__super__.init.call(this,a)},b.prototype.startRecord=function(){var a;if("recording"!==(a=this.state)&&"uploading"!==a)return this.recordRTC?(this._changstate("recording"),this.trigger("record:started"),this.recordRTC.blob=null,this.duration=null,this.recordRTC.startRecording(),this.startTime=(new Date).getTime(),this.recordTimer=setTimeout(function(a){return function(){return a.stopRecord()}}(this),6e4)):this.requestPermission("startRecord")},b.prototype.stopRecord=function(){return"recording"!==this.state?console.warn("You have to perform when you record."):this.recordRTC?this.recordRTC.stopRecording(function(a){return function(b){return a._changstate("recorded"),a._stopHandler()}}(this)):this.requestPermission("stopRecord")},b.prototype._stopHandler=function(){return null!=this.recordTimer&&clearTimeout(this.recordTimer),this.duration||(this.duration=(new Date).getTime()-this.startTime),this.trigger("record:stopped",this.recordRTC.getBlob(),this.duration)},b.prototype.send=function(){return"uploading"===this.state?console.warn("Please wait for the upload."):this.recordRTC?this.recordRTC.stopRecording(function(a){return function(b){var c;return c=a.recordRTC.getBlob(),null!=c&&a._uploader.addFile(c),a._stopHandler()}}(this)):this.requestPermission()},b}(d),b.exports=e},{"./uploader":21,debug:38}],24:[function(a,b,c){"use strict";var d,e,f,g;g=a("debug")("engine:chat:users"),f=a("../chatManagerUtil"),d=a("../../utils/promise"),e=function(){function a(a){this.engine=a}return a.prototype.loadGroupUsers=function(a){return this._getGroupUsers(a)},a.prototype._getGroupUsers=function(a){return this.engine.chatManager.request("engine_chat:group:getUsers",a)},a}(),d.toPromise(e),b.exports=e},{"../../utils/promise":32,"../chatManagerUtil":10,debug:38}],25:[function(a,b,c){(function(c){"use strict";var d,e,f,g,h,i,j,k=function(a,b){function c(){this.constructor=a}for(var d in b)l.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},l={}.hasOwnProperty;i=a("debug")("engine:connection"),j=a("engine.io-client"),e=a("../utils/eventEmitter"),g=a("./serverAddrManager"),h=a("../utils"),f=a("../protocol"),d=function(a){function b(a){this.engine=a,this._serverAddrManager=new g(this.engine),this._updateState("initialized"),this._connect()}return k(b,a),b.prototype._updateState=function(a){var b;return b=this.state,a!==b?(this.state=a,c.nextTick(function(c){return function(){return c.trigger("state_changed",{previous:b,current:a}),c.trigger(a)}}(this))):void 0},b.prototype._handleConnectionEvent=function(a){switch(a.name){case"engine_connection:established":return this.socketId=this._socket.id,this._updateState("connected");case"engine_connection:error":return this._lastEngineError=a.data,this.trigger("error",{code:a.data.code,message:a.data.message})}},b.prototype._handleResponseEvent=function(a){var b;return(b=this._socket.pendingCallbacks[a.data.to])?(delete this._socket.pendingCallbacks[a.data.to],a.data.ok?(b(null,a.data.result),b.needSendAck?this.sendResponseEvent(a.id):void 0):b(a.data.error)):void 0},b.prototype._connect=function(a){var b,c,d,g,k,l,m,n,o,p;if(o=(null!=(m=this.engine.options)?m.serverAddr:void 0)||this._serverAddrManager.addr,!o)return this._socket=new e,this._serverAddrManager.refresh(),void this._serverAddrManager.bindOnce("refreshed",function(a){return function(b){return b?(a._lastEngineError=b,a._socket.emit("close"),a._socket=null):a._connect()}}(this));if(d=this._socket,this._socket=new j.Socket(o,{query:{appId:this.engine.appId,platform:h.getPlatform(),sdkVersion:this.engine.version,protocol:f.version}}),this._socket.pendingCallbacks={},p=(new Date).getTime(),this._socket.on("open",function(){var a;return a=(new Date).getTime(),i("socket open",a-p+"ms")}),this._socket.on("message",function(a){return function(b){var c,d,e;try{e=f.decodeEvent(b)}catch(d){return c=d,a.trigger("error",c)}return i("got event",e),f.connectionEventNamePattern.test(e.name)?a._handleConnectionEvent(e):f.responseEventNamePattern.test(e.name)?a._handleResponseEvent(e):a.trigger("event",e)}}(this)),this._socket.on("close",function(a){return function(b){var c,d,e;i("socket close",b),e=a._socket.pendingCallbacks;for(d in e)(c=e[d])(f.responseErrors.noConnection);return a._socket=null,a.socketId=null}}(this)),this._socket.on("error",function(a){return i("socket error",a)}),this._socket.on("upgradeError",function(a){return i("socket upgradeError",a)}),d){for(b=["open","message","close","error","flush","drain","upgradeError","upgrade"],n=[],g=0,k=b.length;k>g;g++)c=b[g],n.push(function(){var a,b,e,f;for(e=d.listeners(c),f=[],a=0,b=e.length;b>a;a++)l=e[a],f.push(this._socket.on(c,l));return f}.call(this));return n}},b.prototype.sendEvent=function(a,b,c){var d;return"function"==typeof b&&(c=b,b=null),"connected"!==this.state?c?setTimeout(function(){return c(f.responseErrors.noConnection)},0):!1:(null==this.eventId&&(this.eventId=0),this.eventId++,d=f.encodeEvent({id:this.eventId,name:a,data:b}),i("send event",{id:this.eventId,name:a,data:b}),this._socket.send(d),c?c?this._socket.pendingCallbacks[this.eventId]=c:void 0:!0)},b.prototype.sendResponseEvent=function(a,b,c){var d;return d={to:a},b?(d.ok=!1,d.err=b):(d.ok=!0,c&&(d.result=c)),this.sendEvent("engine_response",d)},b.prototype.disconnect=function(){var a;return null!=(a=this._socket)&&"function"==typeof a.close&&a.close(),this._updateState("disconnected")},b.prototype.connect=function(){return"disconnected"===this.state?this._connect():void 0},b}(e),b.exports=d}).call(this,a("_process"))},{"../protocol":29,"../utils":31,"../utils/eventEmitter":30,"./serverAddrManager":27,_process:78,debug:38,"engine.io-client":41}],26:[function(a,b,c){"use strict";var d,e,f,g=function(a,b){function c(){this.constructor=a}for(var d in b)h.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},h={}.hasOwnProperty;f=a("debug")("engine:connection"),e=a("./connection"),d=function(a){function b(a){this.engine=a,b.__super__.constructor.call(this,this.engine),this._resetReconnectState()}return g(b,a),b.prototype._resetReconnectState=function(){return this._reconnectState={count:0,startTime:null,strategy:"backoff","in":0,inMax:1e4},null!=this._reconnectTimer?(clearTimeout(this._reconnectTimer),this._reconnectTimer=null):void 0},b.prototype._reconnect=function(a,b,c){var d,e,g,h,i,j,k;if("disconnected"!==(h=this.state)&&"failed"!==h&&!this._reconnectTimer){if(this._lastEngineError){if(g=this._lastEngineError,this._lastEngineError=null,4e3<=(i=g.code)&&4099>=i)return this._updateState("failed");if(4100<=(j=g.code)&&4199>=j)return g.reconnectRefreshServerAddr&&this._serverAddrManager.refresh(),this._reconnect(g.reconnectStrategy,g.reconnectIn,g.reconnectInMax);if(4200<=(k=g.code)&&4399>=k)return this._reconnect()}switch((e=this._reconnectState).startTime||(e.startTime=new Date),this._reconnectState.strategy=a||this._reconnectState.strategy,this._reconnectState["in"]=null!=b?b:this._reconnectState["in"],this._reconnectState.inMax=null!=c?c:this._reconnectState.inMax,this._reconnectState.strategy){case"backoff":d=this._reconnectState.count>0?2*this._reconnectState["in"]||1:this._reconnectState["in"],this._reconnectState["in"]=Math.min(this._reconnectState.inMax,d);break;case"static":this._reconnectState["in"]=null!=b?b:this._reconnectState["in"]}return this._reconnectTimer=setTimeout(function(a){return function(){return a._reconnectTimer=null,a._serverAddrManager.refresh(),a._connect(),a._reconnectState.count++}}(this),this._reconnectState["in"]),f("reconnect",this._reconnectState),this.trigger("connecting_in",this._reconnectState["in"]),this._updateState("connecting")}},b.prototype._connect=function(){return this._updateState("connecting"),b.__super__._connect.call(this),this._socket.on("open",function(a){return function(){return a._resetReconnectState()}}(this)),this._socket.on("close",function(a){return function(){return a._reconnect()}}(this))},b.prototype.disconnect=function(){return b.__super__.disconnect.call(this),this._resetReconnectState()},b}(e),b.exports=d},{"./connection":25,debug:38}],27:[function(a,b,c){"use strict";var d,e,f,g,h,i=function(a,b){function c(){this.constructor=a}for(var d in b)j.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},j={}.hasOwnProperty;h=a("debug")("engine:connection:serverAddrManager"),d=a("../utils/eventEmitter"),f=a("../utils/requester"),e="https://api.tuisongbao.com:443/v2/sdk/engine/server",g=function(a){function b(a){this.engine=a,this._refreshing=!1}return i(b,a),b.prototype.refresh=function(){var a;if(!this._refreshing)return this.addr=null,this._refreshing=!0,a=(new Date).getTime(),f.getWithJSONPFallback(e,{appId:this.engine.appId},function(b){return function(c,d){var e;return e=(new Date).getTime(),h("Got server addr response",{err:c,res:d,elapsed:e-a+"ms"}),b._refreshing=!1,c?b.trigger("refreshed",c):(b.addr=d.addr,b.trigger("refreshed"))}}(this),this.engine.options)},b}(d),b.exports=g},{"../utils/eventEmitter":30,"../utils/requester":33,debug:38}],28:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n=[].slice;l=a("debug").log,a("debug").log=function(){var a,b,c;return b=1<=arguments.length?n.call(arguments,0):[],c=function(){var c,d,e;for(e=[],c=0,d=b.length;d>c;c++){a=b[c];try{a instanceof Error?e.push(a):e.push(JSON.stringify(a))}catch(f){e.push(a)}}return e}(),l.apply(this,c)},m=a("debug")("engine:index"),k=a("./utils"),g=a("./connection"),d=a("./authorizer"),e=a("./channels"),f=a("./chat"),j=a("./protocol"),i=a("./utils/promise"),h=function(){function b(a,b){this.appId=a,this.options=b,this.appId||k.throwError("appId is required."),this.version="v2.1.0",this.connection=new g(this),this.authorizer=new d(this),this.channels=new e(this),this.chatManager=new f(this),"undefined"!=typeof window&&null!==window&&null==window.Promise&&(window.Promise=i),this.connection.bind("state_changed",function(a){return m("connection state_changed",a)}),this.connection.bind("connecting_in",function(a){return m("connection connecting_in",a)}),this.connection.bind("connected",function(a){return function(){return a.channels.subscribeAll(),a.chatManager.autoLogin()}}(this)),this.connection.bind("event",function(a){return function(b){var c;return b.channel?(c=a.channels.find(b.channel),c.handleEvent(b)):j.chatEventNamePattern.test(b.name)?a.chatManager.handleEvent(b):void 0}}(this)),this.connection.bind("error",function(a){return m("connection error",a)}),this.connection.bind("disconnected",function(a){return function(){return a.chatManager.handleNoConnectionOperations(!0),a.channels.disconnect()}}(this))}return b.debug=a("debug"),b}(),"undefined"!=typeof window&&null!==window&&(window.Engine=h),b.exports=h},{"./authorizer":1,"./channels":3,"./chat":17,"./connection":26,"./protocol":29,"./utils":31,"./utils/promise":32,debug:38}],29:[function(a,b,c){"use strict";var d,e,f,g=function(a,b){function c(){this.constructor=a}for(var d in b)h.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},h={}.hasOwnProperty;d=a("../protocol"),f=a("./utils"),e=function(a){function b(){return b.__super__.constructor.apply(this,arguments)}return g(b,a),b._throwError=f.throwError,b}(d),b.exports=e},{"../protocol":37,"./utils":31}],30:[function(a,b,c){"use strict";var d,e,f=function(a,b){function c(){this.constructor=a}for(var d in b)g.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},g={}.hasOwnProperty;e=a("events"),d=function(a){function b(){return b.__super__.constructor.apply(this,arguments)}return f(b,a),b.prototype.bind=function(){return this.on.apply(this,arguments)},b.prototype.bindOnce=function(){return this.once.apply(this,arguments)},b.prototype.unbind=function(a,b){return b?this.removeListener(a,b):this.removeAllListeners(a)},b.prototype.trigger=function(){return this.emit.apply(this,arguments)},b.prototype.handlers=function(){return this.listeners.apply(this,arguments)},b}(e.EventEmitter),b.exports=d},{events:77}],31:[function(a,b,c){(function(a){"use strict";var c;c=function(){function b(){}return b.createError=function(a){
3 | var b;return b=new Error(a.message||a),b.name="EngineError",null==b.code&&(b.code=a.code||-1),b},b.throwError=function(a){throw b.createError(a)},b.genRandomStr=function(){var a,b,c;return b="abcdefghijklmnopqrstuvwxyz_",c=function(){var c,d;for(d=[],a=c=0;20>c;a=++c)d.push(b[Math.floor(Math.random()*b.length)]);return d}(),c.join("")},b.checkBrowser=function(){var a,b,c,d;return"undefined"==typeof window||null===window?function(){return{}}:(d=window.navigator.userAgent.toLowerCase(),a=/(edge)\/([\w.]+)/.exec(d)||/(opr)[\/]([\w.]+)/.exec(d)||/(chrome)[ \/]([\w.]+)/.exec(d),a||(a=/(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(d)),a||(a=/(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(d)),a||(a=/(webkit)[ \/]([\w.]+)/.exec(d)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(d)),a||(a=/(msie) ([\w.]+)/.exec(d)||d.indexOf("trident")>=0&&/(rv)(?::| )([\w.]+)/.exec(d)),a||(a=d.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(d)||[]),b=/(ipad)/.exec(d)||/(ipod)/.exec(d)||/(iphone)/.exec(d)||/(kindle)/.exec(d),b||(b=/(silk)/.exec(d)||/(android)/.exec(d)||/(windows phone)/.exec(d)||/(win)/.exec(d)),b||(b=/(mac)/.exec(d)||/(linux)/.exec(d)||/(cros)/.exec(d)||/(playbook)/.exec(d)),b||(b=/(bb)/.exec(d)||/(blackberry)/.exec(d)||[]),c={browser:a[5]||a[3]||a[1]||"",version:a[2]||a[4]||"0",versionNumber:a[4]||a[2]||"0",platform:b[0]||""},function(){return c})}(),b.getPlatform=function(){var b;return b="undefined"!=typeof window&&null!==window?window.navigator.userAgent:"Node.js "+a.version+"$"+a.platform+"$"+a.arch,function(){return b}}(),b}(),b.exports=c}).call(this,a("_process"))},{_process:78}],32:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n={}.hasOwnProperty;j=a("debug")("engine:promise"),h=a("../utils"),i=a("../chat/chatManagerUtil"),e=void 0,d=1,g=2,l=function(a){return"function"==typeof a},k=function(a){return"[object Array]"===Object.prototype.toString.call(a)},m=function(a){return a&&"function"==typeof a.then},f=function(){function a(b){var c,f;if(!l(b))throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");return this instanceof a?(this._value,this._reason,this._status=e,this._resolveHandlers=[],this._rejectHandlers=[],f=function(a){return function(b){return a.transite(d,b)}}(this),c=function(a){return function(b){return a.transite(g,b)}}(this),void b(f,c)):new a(b)}return a.prototype.transite=function(a,b){return this._status===e?setTimeout(function(c){return function(){return c._status=a,c._publish(b)}}(this),0):void 0},a.prototype._publish=function(a){var b,c,e;if(e=this._status===d,c=this[e?"_resolveHandlers":"_rejectHandlers"],void 0!==c)for(;b=c.shift();)a=b.call(this,a)||a;return this[e?"_value":"_reason"]=a,this._resolveHandlers=this._rejectHandlers=void 0},a.prototype.then=function(b,c){var f;return f=this,new a(function(a,h){var i,j;return i=function(c){var d,e,f;try{return f=l(b)&&b(c)||c,m(f)?f.then(function(b){return a(b)},function(a){return h(a)}):a(f)}catch(e){return d=e,h(d)}},j=function(a){return a=l(c)&&c(a)||a,h(a)},f._status===e?(f._resolveHandlers.push(i),f._rejectHandlers.push(j)):f._status===d?i(f._value):f._status===g?j(f._reason):void 0})},a.prototype["catch"]=function(a){return this.then(void 0,a)},a.prototype.delay=function(b){return this.then(function(c){return a.delay(b,c)})},a}(),f.delay=function(a,b){return new f(function(c,d){var e,f;try{return setTimeout(function(){return c(b)},a)}catch(f){return e=f,d(e)}})},f.resolve=function(a){return new f(function(b,c){var d,e;try{return b(a)}catch(e){return d=e,c(d)}})},f.reject=function(a){return new f(function(b,c){var d,e;try{return c(a)}catch(e){return d=e,c(d)}})},f.all=function(a){if(!k(a))throw new TypeError("You must pass an array to all.");return new f(function(b,c){var d,e,f,g,h,i,j,k;if(d=0,j=[],e=a.length,0===e)return b([]);for(i=function(a){return function(b){return h(a,b)}},g=function(a){return c(a)},h=function(a,c){return j[a]=c,a===e-1?b(j):void 0},k=[];e>d;)null!=(f=a[d])&&"function"==typeof f.then&&f.then(i(d),g),k.push(d++);return k})},f.toPromise=function(a,b,c){var d,e,g,k;e=a.prototype,g=[];for(d in e)n.call(e,d)&&(k=e[d],l(k)&&"constructor"!==d&&((null!=b?b.indexOf(d):void 0)<0||(null!=c?c.indexOf(d):void 0)>-1||g.push(function(b,c){return a.prototype[b]=function(a){var d,e,g;return null==a&&(a={}),null!=a.onSuccess||null!=a.onError||"object"!=typeof a?("object"==typeof a&&l(a.onError)&&(d=a.onError,a.onError=function(a){return a=h.createError(a),j(b+":"+c,a),d(a)}),c.apply(this,arguments)):arguments.length>1?c.apply(this,arguments):(e=i.getPromiseOption(a),g=new f(function(a,d){return e.onSuccess=function(b){return a(b)},e.onError=function(a){return a=h.createError(a),j(b+":"+c,a),d(a)}}),c.call(this,e),g)}}(d,k))));return g},b.exports=f},{"../chat/chatManagerUtil":10,"../utils":31,debug:38}],33:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m;h=a("debug")("engine:utils:requester"),l=a("superagent"),j=a("./jsonpRequest"),m=a("./xmlHttpRequest"),f=a("../index"),g=f.checkBrowser(),k="msie"===g.browser&&parseFloat(g.versionNumber)<10?!0:!1,i=function(a,b){var c,d,e;b.timestamp=(new Date).getTime(),d=[];for(c in b)e=b[c],d.push(c+"="+e);return a+=-1===a.indexOf("?")?"?":"&",a+=d.join("&")},d=function(){function a(){}return a.get=function(a,b,c){return"function"==typeof b&&(c=b,b={}),a=i(a,b),h("xmlHttpRequest.get",{url:a,data:b}),m.get(a,c)},a.getWithJSONPFallback=function(a,b,c){var d;return(d=k?this.jsonp:this.get)(a,b,c)},a.post=function(a,b,c){return"function"==typeof b&&(c=b,b={}),h("xmlHttpRequest.post",{url:a,data:b}),m.post(a,b,c)},a.postWithJSONPFallback=function(a,b,c){var d;return(d=k?this.jsonp:this.post)(a,b,callback)},a.jsonp=function(a,b,c){return"function"==typeof b&&(c=b,b={}),b.callback||(b.callback=f.genRandomStr()),a=i(a,b),h("jsonp",{url:a,data:b}),j.get(a,c)},a}(),e=function(){function a(){}return a.get=function(a,b,c){return l.get(a).query(b).end(function(a,b){return c(a,null!=b?b.body:void 0)})},a.getWithJSONPFallback=a.get,a.post=function(a,b,c){return l.post(a).send(b).end(function(a,b){return c(a,null!=b?b.body:void 0)})},a.postWithJSONPFallback=a.post,a}(),b.exports="undefined"!=typeof window&&null!==window?d:e},{"../index":31,"./jsonpRequest":34,"./xmlHttpRequest":36,debug:38,superagent:72}],34:[function(a,b,c){"use strict";var d,e;e=a("./loadJS.coffee"),d=function(a){var b,c;if(b=/[\?|&]callback=([a-z0-9_]+)/i,c=a.match(b),!c)throw new Error("Could not find callback on URL");return c[1]},b.exports.get=function(a,b){var c,f,g,h,i;try{c=d(a)}catch(h){return g=h,b(g)}return f=void 0,i=window[c],window[c]=function(a){return f=a},e.load(a).then(function(){return b(null,f)})["catch"](function(a){var d;if(a||f||(a=new Error("JSONP requeset can not get a JSON response")),i)window[c]=i;else try{delete window[c]}catch(d){a=d,window[c]=void 0}return b(a,f)})}},{"./loadJS.coffee":35}],35:[function(a,b,c){"use strict";var d,e,f,g;e=a("../promise"),f=a("debug")("engine:loadJS"),d=function(){function a(){this.loaded={}}return a.prototype.load=function(){var a,b,c,d,f;if(0===arguments.length)return e.reject("arguments error");for(f=[],c=0,d=arguments.length;d>c;c++)b=arguments[c],b instanceof Array?f=function(){var c,d,e;for(e=[],c=0,d=b.length;d>c;c++)a=b[c],e.push(this._load(a));return e}.call(this):f.push(this._load(b));return e.all(f)},a.prototype._load=function(a){var b,c;return c=this,b=new e(function(b,d){var e,g,h,i;return"loaded"===c.loaded[a]?b("loaded"):"loading"===c.loaded[a]?void(i=setInterval(function(){return"loaded"===c.loaded[a]?(null!=i&&clearInterval(i),b("loaded")):void 0},2e3)):(c.loaded[a]="loading",e=document.getElementsByTagName("head")[0],g=document.createElement("script"),g.type="text/javascript",g.src=a,g.async=!0,h=setTimeout(function(){return d("请求超时")},1e4),g.onreadystatechange=g.onload=function(d){return c.loaded[a]="loaded",null!=h&&clearTimeout(h),b(a)},g.onerror=function(b){return c.loaded[a]="error",f("loadJS error",a,b),null!=h&&clearTimeout(h),d(new Error(b))},e.appendChild(g))})},a.prototype.getExtensionJS=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o;if(l={enableCache:["indexeddbshim.min.js","db.min.js"],enableMediaMessage:["plupload.min.js","qiniu.min.js","RecordRTC.js"]},c=[],"[object Array]"===Object.prototype.toString.call(a)){for(d=0,h=a.length;h>d;d++)if(b=a[d],l[b])for(m=l[b],e=0,i=m.length;i>e;e++)k=m[e],c.push(k)}else for(f in a)if(o=a[f],"function"!=typeof o&&o)for(n=l[f],g=0,j=n.length;j>g;g++)k=n[g],c.push(k);return c},a.prototype.getExtensionJSPaths=function(a,b){var c;return c=new RegExp("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&?/.=]+(js)$"),c.test(a)?a:(this.basePath=b||"/",null==this.basePath&&this.throwError("If you want to use the extension, You must specify the base path!"),b="/"===this.basePath.charAt(this.basePath.length-1)?this.basePath+"libs/":this.basePath+"/libs/",""+b+a)},a.prototype.requireExtensionJSPaths=function(a,b){var c,d,e,f,g;for(d=[],g=this.getExtensionJS([a]),e=0,f=g.length;f>e;e++)c=g[e],d.push(this.getExtensionJSPaths(c));return d},a.prototype.require=function(a,b){var c,d,e,f,g;for(d=[],g=this.getExtensionJS([a]),e=0,f=g.length;f>e;e++)c=g[e],d.push(this.getExtensionJSPaths(c,b));return this.load(d)},a}(),g=new d,b.exports=g},{"../promise":32,debug:38}],36:[function(a,b,c){"use strict";var d,e;d=function(){try{if(window.XMLHttpRequest)return new XMLHttpRequest}catch(a){}},e=function(a,b,c,e,f){var g,h,i,j,k;null==c&&(c={}),k=d(),k.open(a,b,!0);for(i in c)j=c[i],k.setRequestHeader(i,j);k.onload=function(){var a,b,c;if(4===k.readyState){if(200!==k.status)return f(new Error("Unexpected response, status: "+k.status));try{c=JSON.parse(k.responseText)}catch(b){return a=b,f(a)}return f(null,c)}},k.onerror=function(){return f(new Error("Unexpected response, status: "+k.status))};try{return k.send(e)}catch(h){return g=h,f(g)}},c.get=function(a,b){return e("GET",a,null,null,b)},c.post=function(a,b,c){var d;return d={"Content-Type":"application/json"},b=JSON.stringify(b),e("POST",a,d,b,c)}},{}],37:[function(a,b,c){(function(a){"use strict";var c,d=[].indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(b in this&&this[b]===a)return b;return-1};c=function(){function b(){}return b.version="v1",b.eventNameMaxLength=128,b.eventDataMaxSize=10240,b.channelNamePattern=new RegExp("^[a-zA-Z0-9_\\-=@,.;]+$"),b.channelNameFullPattern=new RegExp("^[a-zA-Z0-9_\\-=@,.;]{1,128}$"),b.privateChannelNameFullPattern=new RegExp("^private-[a-zA-Z0-9_\\-=@,.;]{0,120}$"),b.presenceChannelNameFullPattern=new RegExp("^presence-[a-zA-Z0-9_\\-=@,.;]{0,119}$"),b.channelNameMaxLength=128,b.presenceChannelUserMaxCount=1e3,b.presenceChannelUserIdMaxLength=128,b.presenceChannelUserInfoMaxSize=1024,b.internalEventNamePattern=new RegExp("^engine_.*"),b.connectionEventNamePattern=new RegExp("^engine_connection"),b.channelEventNamePattern=new RegExp("^engine_channel"),b.chatEventNamePattern=new RegExp("^engine_chat"),b.responseEventNamePattern=new RegExp("^engine_response$"),b.connErrors={requestInvalid:{code:4e3,message:"Request is invalid."},requestProtocolNotSupported:{code:4001,message:"Request protocol is not supported."},eventInvalid:{code:4010,message:"Event is invalid."},eventNameTooLong:{code:4011,message:"Event name is too long."},eventDataTooBig:{code:4012,message:"Event data is too big."},appNotExists:{code:4020,message:"App does not exist."},appDisabled:{code:4021,message:"App is disabled."},serverInternalError:{code:4100,message:"Server internal error, please try again later.",reconnectStrategy:"static",reconnectIn:6e4},serverMaintenance:{code:4101,message:"Server is under maintenance, please try again later.",reconnectStrategy:"backoff",reconnectIn:3e4,reconnectInMax:3e5},serverOverCapacity:{code:4102,message:"Server is over capacity, please try again later.",reconnectStrategy:"backoff",reconnectIn:1e4,reconnectInMax:3e5},appOverConnectionQuota:{code:4110,message:"App is over connection quota, please try again later.",reconnectStrategy:"static",reconnectIn:6e5}},b.responseErrors={noConnection:{code:4500,message:"Connection is not available, please check your network configuration."},serverInternalError:{code:4501,message:"Server internal error, please try again later."},incorrectSignature:{code:4502,message:"Incorrect signature."},unauthorized:{code:4503,message:"Unauthorized, please login first."},invalidRequest:{code:4504,message:"Invalid request."},permissionDenied:{code:4505,message:"Permission denied."},fileOperationFailed:{code:4506,message:"File operation failed."},requestTimeout:{code:4507,message:"Request timed out."}},b._throwError=function(a){throw a},b._validateEvent=function(b,c){var d;return b.id&&b.name||this._throwError(this.connErrors.eventInvalid),b.name.length>this.eventNameMaxLength&&this._throwError(this.connErrors.eventNameTooLong),c?(d=a.byteLength(JSON.stringify(b.data),"utf8"),d>this.eventDataMaxSize?this._throwError(this.connErrors.eventDataTooBig):void 0):void 0},b.decodeEvent=function(a){var b,c;try{a=JSON.parse(a)}catch(c){b=c,this._throwError(this.connErrors.eventInvalid)}return this._validateEvent(a),a},b.encodeEvent=function(a,b){return null==b&&(b=!0),this._validateEvent(a,b),JSON.stringify(a)},b.validateChannel=function(a){var b;return a||this._throwError(new Error("Channel name is required.")),this.channelNamePattern.test(a)||this._throwError(new Error("Channel name contains invalid character.")),a.length>this.channelNameMaxLength&&this._throwError(new Error("Channel name is too long.")),b="channel",this.privateChannelNameFullPattern.test(a)?b="privateChannel":this.presenceChannelNameFullPattern.test(a)&&(b="presenceChannel"),b},b.validatePresenceChannelUser=function(b,c){var e,f,g;return f=_.unique(b),f.length>=this.presenceChannelUserMaxCount&&(e=c.userId,d.call(f,e)<0)&&this._throwError(new Error("Exceeds max presence channel user count.")),g=a.byteLength(JSON.stringify(c.userInfo),"utf8"),g>this.presenceChannelUserInfoMaxSize?this._throwError(new Error("Exceeds max user info size.")):void 0},b}(),b.exports=c}).call(this,a("buffer").Buffer)},{buffer:73}],38:[function(a,b,c){function d(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)}function e(){var a=arguments,b=this.useColors;if(a[0]=(b?"%c":"")+this.namespace+(b?"%c ":" ")+a[0]+(b?"%c ":" ")+"+"+c.humanize(this.diff),b){var d="color: "+this.color;a=[a[0],d,""].concat(Array.prototype.slice.call(a,1));var e=0,f=0;a[0].replace(/%[a-z%]/g,function(a){"%%"!==a&&(e++,"%c"===a&&(f=e))}),a.splice(f,0,d)}return"object"==typeof console&&"function"==typeof console.log&&Function.prototype.apply.call(console.log,console,a)}function f(a){try{null==a?localStorage.removeItem("debug"):localStorage.debug=a}catch(b){}}function g(){var a;try{a=localStorage.debug}catch(b){}return a}c=b.exports=a("./debug"),c.log=e,c.save=f,c.load=g,c.useColors=d,c.colors=["cyan","green","goldenrod","blue","purple","red"],c.formatters.j=function(a){return JSON.stringify(a)},c.enable(g())},{"./debug":39}],39:[function(a,b,c){function d(){return c.colors[k++%c.colors.length]}function e(a){function b(){}function e(){var a=e,b=+new Date,f=b-(j||b);a.diff=f,a.prev=j,a.curr=b,j=b,null==a.useColors&&(a.useColors=c.useColors()),null==a.color&&a.useColors&&(a.color=d());var g=Array.prototype.slice.call(arguments);g[0]=c.coerce(g[0]),"string"!=typeof g[0]&&(g=["%o"].concat(g));var h=0;g[0]=g[0].replace(/%([a-z%])/g,function(b,d){if("%%"===b)return b;h++;var e=c.formatters[d];if("function"==typeof e){var f=g[h];b=e.call(a,f),g.splice(h,1),h--}return b}),c.log.apply(a,g)}b.enabled=!1,e.enabled=!0;var f=c.enabled(a)?e:b;return f.namespace=a,f}function f(a){c.save(a);for(var b=(a||"").split(/[\s,]+/),d=b.length,e=0;d>e;e++)b[e]&&(a=b[e].replace("*",".*?"),"-"===a[0]?c.skips.push(new RegExp("^"+a.substr(1)+"$")):c.names.push(new RegExp("^"+a+"$")))}function g(){c.enable("")}function h(a){var b,d;for(b=0,d=c.skips.length;d>b;b++)if(c.skips[b].test(a))return!1;for(b=0,d=c.names.length;d>b;b++)if(c.names[b].test(a))return!0;return!1}function i(a){return a instanceof Error?a.stack||a.message:a}c=b.exports=e,c.coerce=i,c.disable=g,c.enable=f,c.enabled=h,c.humanize=a("ms"),c.names=[],c.skips=[],c.formatters={};var j,k=0},{ms:40}],40:[function(a,b,c){function d(a){var b=/^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(a);if(b){var c=parseFloat(b[1]),d=(b[2]||"ms").toLowerCase();switch(d){case"years":case"year":case"y":return c*l;case"days":case"day":case"d":return c*k;case"hours":case"hour":case"h":return c*j;case"minutes":case"minute":case"m":return c*i;case"seconds":case"second":case"s":return c*h;case"ms":return c}}}function e(a){return a>=k?Math.round(a/k)+"d":a>=j?Math.round(a/j)+"h":a>=i?Math.round(a/i)+"m":a>=h?Math.round(a/h)+"s":a+"ms"}function f(a){return g(a,k,"day")||g(a,j,"hour")||g(a,i,"minute")||g(a,h,"second")||a+" ms"}function g(a,b,c){return b>a?void 0:1.5*b>a?Math.floor(a/b)+" "+c:Math.ceil(a/b)+" "+c+"s"}var h=1e3,i=60*h,j=60*i,k=24*j,l=365.25*k;b.exports=function(a,b){return b=b||{},"string"==typeof a?d(a):b["long"]?f(a):e(a)}},{}],41:[function(a,b,c){b.exports=a("./lib/")},{"./lib/":42}],42:[function(a,b,c){b.exports=a("./socket"),b.exports.parser=a("engine.io-parser")},{"./socket":43,"engine.io-parser":56}],43:[function(a,b,c){(function(c){function d(a,b){if(!(this instanceof d))return new d(a,b);if(b=b||{},a&&"object"==typeof a&&(b=a,a=null),a&&(a=k(a),b.host=a.host,b.secure="https"==a.protocol||"wss"==a.protocol,b.port=a.port,a.query&&(b.query=a.query)),this.secure=null!=b.secure?b.secure:c.location&&"https:"==location.protocol,b.host){var e=b.host.split(":");b.hostname=e.shift(),e.length?b.port=e.pop():b.port||(b.port=this.secure?"443":"80")}this.agent=b.agent||!1,this.hostname=b.hostname||(c.location?location.hostname:"localhost"),this.port=b.port||(c.location&&location.port?location.port:this.secure?443:80),this.query=b.query||{},"string"==typeof this.query&&(this.query=m.decode(this.query)),this.upgrade=!1!==b.upgrade,this.path=(b.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!b.forceJSONP,this.jsonp=!1!==b.jsonp,this.forceBase64=!!b.forceBase64,this.enablesXDR=!!b.enablesXDR,this.timestampParam=b.timestampParam||"t",this.timestampRequests=b.timestampRequests,this.transports=b.transports||["polling","websocket"],this.readyState="",this.writeBuffer=[],this.callbackBuffer=[],this.policyPort=b.policyPort||843,this.rememberUpgrade=b.rememberUpgrade||!1,this.binaryType=null,this.onlyBinaryUpgrades=b.onlyBinaryUpgrades,this.pfx=b.pfx||null,this.key=b.key||null,this.passphrase=b.passphrase||null,this.cert=b.cert||null,this.ca=b.ca||null,this.ciphers=b.ciphers||null,this.rejectUnauthorized=b.rejectUnauthorized||null,this.open()}function e(a){var b={};for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);return b}var f=a("./transports"),g=a("component-emitter"),h=a("debug")("engine.io-client:socket"),i=a("indexof"),j=a("engine.io-parser"),k=a("parseuri"),l=a("parsejson"),m=a("parseqs");b.exports=d,d.priorWebsocketSuccess=!1,g(d.prototype),d.protocol=j.protocol,d.Socket=d,d.Transport=a("./transport"),d.transports=a("./transports"),d.parser=a("engine.io-parser"),d.prototype.createTransport=function(a){h('creating transport "%s"',a);var b=e(this.query);b.EIO=j.protocol,b.transport=a,this.id&&(b.sid=this.id);var c=new f[a]({agent:this.agent,hostname:this.hostname,port:this.port,secure:this.secure,path:this.path,query:b,forceJSONP:this.forceJSONP,jsonp:this.jsonp,forceBase64:this.forceBase64,enablesXDR:this.enablesXDR,timestampRequests:this.timestampRequests,timestampParam:this.timestampParam,policyPort:this.policyPort,socket:this,pfx:this.pfx,key:this.key,passphrase:this.passphrase,cert:this.cert,ca:this.ca,ciphers:this.ciphers,rejectUnauthorized:this.rejectUnauthorized});return c},d.prototype.open=function(){var a;if(this.rememberUpgrade&&d.priorWebsocketSuccess&&-1!=this.transports.indexOf("websocket"))a="websocket";else{if(0==this.transports.length){var b=this;return void setTimeout(function(){b.emit("error","No transports available")},0)}a=this.transports[0]}this.readyState="opening";var a;try{a=this.createTransport(a)}catch(c){return this.transports.shift(),void this.open()}a.open(),this.setTransport(a)},d.prototype.setTransport=function(a){h("setting transport %s",a.name);var b=this;this.transport&&(h("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=a,a.on("drain",function(){b.onDrain()}).on("packet",function(a){b.onPacket(a)}).on("error",function(a){b.onError(a)}).on("close",function(){b.onClose("transport close")})},d.prototype.probe=function(a){function b(){if(m.onlyBinaryUpgrades){var b=!this.supportsBinary&&m.transport.supportsBinary;l=l||b}l||(h('probe transport "%s" opened',a),k.send([{type:"ping",data:"probe"}]),k.once("packet",function(b){if(!l)if("pong"==b.type&&"probe"==b.data){if(h('probe transport "%s" pong',a),m.upgrading=!0,m.emit("upgrading",k),!k)return;d.priorWebsocketSuccess="websocket"==k.name,h('pausing current transport "%s"',m.transport.name),m.transport.pause(function(){l||"closed"!=m.readyState&&(h("changing transport and sending upgrade packet"),j(),m.setTransport(k),k.send([{type:"upgrade"}]),m.emit("upgrade",k),k=null,m.upgrading=!1,m.flush())})}else{h('probe transport "%s" failed',a);var c=new Error("probe error");c.transport=k.name,m.emit("upgradeError",c)}}))}function c(){l||(l=!0,j(),k.close(),k=null)}function e(b){var d=new Error("probe error: "+b);d.transport=k.name,c(),h('probe transport "%s" failed because of error: %s',a,b),m.emit("upgradeError",d)}function f(){e("transport closed")}function g(){e("socket closed")}function i(a){k&&a.name!=k.name&&(h('"%s" works - aborting "%s"',a.name,k.name),c())}function j(){k.removeListener("open",b),k.removeListener("error",e),k.removeListener("close",f),m.removeListener("close",g),m.removeListener("upgrading",i)}h('probing transport "%s"',a);var k=this.createTransport(a,{probe:1}),l=!1,m=this;d.priorWebsocketSuccess=!1,k.once("open",b),k.once("error",e),k.once("close",f),this.once("close",g),this.once("upgrading",i),k.open()},d.prototype.onOpen=function(){if(h("socket open"),this.readyState="open",d.priorWebsocketSuccess="websocket"==this.transport.name,this.emit("open"),this.flush(),"open"==this.readyState&&this.upgrade&&this.transport.pause){h("starting upgrade probes");for(var a=0,b=this.upgrades.length;b>a;a++)this.probe(this.upgrades[a])}},d.prototype.onPacket=function(a){if("opening"==this.readyState||"open"==this.readyState)switch(h('socket receive: type "%s", data "%s"',a.type,a.data),this.emit("packet",a),this.emit("heartbeat"),a.type){case"open":this.onHandshake(l(a.data));break;case"pong":this.setPing();break;case"error":var b=new Error("server error");b.code=a.data,this.emit("error",b);break;case"message":this.emit("data",a.data),this.emit("message",a.data)}else h('packet received with socket readyState "%s"',this.readyState)},d.prototype.onHandshake=function(a){this.emit("handshake",a),this.id=a.sid,this.transport.query.sid=a.sid,this.upgrades=this.filterUpgrades(a.upgrades),this.pingInterval=a.pingInterval,this.pingTimeout=a.pingTimeout,this.onOpen(),"closed"!=this.readyState&&(this.setPing(),this.removeListener("heartbeat",this.onHeartbeat),this.on("heartbeat",this.onHeartbeat))},d.prototype.onHeartbeat=function(a){clearTimeout(this.pingTimeoutTimer);var b=this;b.pingTimeoutTimer=setTimeout(function(){"closed"!=b.readyState&&b.onClose("ping timeout")},a||b.pingInterval+b.pingTimeout)},d.prototype.setPing=function(){var a=this;clearTimeout(a.pingIntervalTimer),a.pingIntervalTimer=setTimeout(function(){h("writing ping packet - expecting pong within %sms",a.pingTimeout),a.ping(),a.onHeartbeat(a.pingTimeout)},a.pingInterval)},d.prototype.ping=function(){this.sendPacket("ping")},d.prototype.onDrain=function(){for(var a=0;ac;c++)~i(this.transports,a[c])&&b.push(a[c]);return b}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./transport":44,"./transports":45,"component-emitter":51,debug:53,"engine.io-parser":56,indexof:67,parsejson:68,parseqs:69,parseuri:70}],44:[function(a,b,c){function d(a){this.path=a.path,this.hostname=a.hostname,this.port=a.port,this.secure=a.secure,this.query=a.query,this.timestampParam=a.timestampParam,this.timestampRequests=a.timestampRequests,this.readyState="",this.agent=a.agent||!1,this.socket=a.socket,this.enablesXDR=a.enablesXDR,this.pfx=a.pfx,this.key=a.key,this.passphrase=a.passphrase,this.cert=a.cert,this.ca=a.ca,this.ciphers=a.ciphers,this.rejectUnauthorized=a.rejectUnauthorized}var e=a("engine.io-parser"),f=a("component-emitter");b.exports=d,f(d.prototype),d.timestamps=0,d.prototype.onError=function(a,b){var c=new Error(a);return c.type="TransportError",c.description=b,this.emit("error",c),this},d.prototype.open=function(){return("closed"==this.readyState||""==this.readyState)&&(this.readyState="opening",this.doOpen()),this},d.prototype.close=function(){return("opening"==this.readyState||"open"==this.readyState)&&(this.doClose(),this.onClose()),this},d.prototype.send=function(a){if("open"!=this.readyState)throw new Error("Transport not open");this.write(a)},d.prototype.onOpen=function(){this.readyState="open",this.writable=!0,this.emit("open")},d.prototype.onData=function(a){var b=e.decodePacket(a,this.socket.binaryType);this.onPacket(b)},d.prototype.onPacket=function(a){this.emit("packet",a)},d.prototype.onClose=function(){this.readyState="closed",this.emit("close")}},{"component-emitter":51,"engine.io-parser":56}],45:[function(a,b,c){(function(b){function d(a){var c,d=!1,h=!1,i=!1!==a.jsonp;if(b.location){var j="https:"==location.protocol,k=location.port;k||(k=j?443:80),d=a.hostname!=location.hostname||k!=a.port,h=a.secure!=j}if(a.xdomain=d,a.xscheme=h,c=new e(a),"open"in c&&!a.forceJSONP)return new f(a);if(!i)throw new Error("JSONP disabled");return new g(a)}var e=a("xmlhttprequest"),f=a("./polling-xhr"),g=a("./polling-jsonp"),h=a("./websocket");c.polling=d,c.websocket=h}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./polling-jsonp":46,"./polling-xhr":47,"./websocket":49,xmlhttprequest:50}],46:[function(a,b,c){(function(c){function d(){}function e(a){f.call(this,a),this.query=this.query||{},h||(c.___eio||(c.___eio=[]),h=c.___eio),this.index=h.length;var b=this;h.push(function(a){b.onData(a)}),this.query.j=this.index,c.document&&c.addEventListener&&c.addEventListener("beforeunload",function(){b.script&&(b.script.onerror=d)},!1)}var f=a("./polling"),g=a("component-inherit");b.exports=e;var h,i=/\n/g,j=/\\n/g;g(e,f),e.prototype.supportsBinary=!1,e.prototype.doClose=function(){this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null,this.iframe=null),f.prototype.doClose.call(this)},e.prototype.doPoll=function(){var a=this,b=document.createElement("script");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),b.async=!0,b.src=this.uri(),b.onerror=function(b){a.onError("jsonp poll error",b)};var c=document.getElementsByTagName("script")[0];c.parentNode.insertBefore(b,c),this.script=b;var d="undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent);d&&setTimeout(function(){var a=document.createElement("iframe");document.body.appendChild(a),document.body.removeChild(a)},100)},e.prototype.doWrite=function(a,b){function c(){d(),b()}function d(){if(e.iframe)try{e.form.removeChild(e.iframe)}catch(a){e.onError("jsonp polling iframe removal error",a)}try{var b='